文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Next Permutation2. Solution
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int index = -1;
int min = 0;
for(int i = nums.size() - 1; i > 0; i--) {
if(nums[i] > nums[i - 1] ) {
index = i - 1;
min = i;
break;
}
}
if(index == -1) {
return reverse(nums.begin(), nums.end());
}
for(int i = index + 1; i < nums.size(); i++) {
if(nums[i] > nums[index] && nums[i] < nums[min]) {
min = i;
}
}
swap(nums[index], nums[min]);
sort(nums.begin() + index + 1, nums.end());
}
private:
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
};
网友评论