Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
思路1:利用STL里面的相关函数即可
void nextPermutation(vector<int>& nums) {
if (nums.size() <= 1)return;
next_permutation(nums.begin(), nums.end());
}
思路2:将STL里面的相关函数具体实现。。。
void nextPermutation(vector<int>& nums) {
if (nums.size() <= 1)return;
int len = nums.size();
for (int i = len - 1; i >= 0; i--){
for (int j = len - 1; j > i; j--){
if (nums[i] < nums[j]){
swap(nums[i], nums[j]);
sort(nums.begin() + i + 1, nums.end());
return;
}
}
}
sort(nums.begin(), nums.end());
return;
}