题目:
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 and use only constant 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
思路:
解该题的关键在于理解题意,有篇分析该题目的博客介绍得比较清楚:分析;
提示:从后往前找数值下降点。
代码:
class Solution {
public:
void nextPermutation(vector<int>& nums) {
if(nums.size() <= 1)return;
if(nums.size() == 2){
swap(nums[0], nums[1]);
return;
}
for(int i = nums.size()-2; i > 0 ; --i){
if(nums[i] < nums[i+1]){
for(int j = i+1; j < nums.size(); ++j){
if(nums[i] >= nums[j]){
swap(nums[i], nums[j-1]);
sort(nums.begin()+i+1, nums.end());
return;
}
if(j == nums.size()-1){
swap(nums[i], nums[j]);
sort(nums.begin()+i+1, nums.end());
return;
}
}
}
}
int id = -1, minv = INT_MAX;
for(int i = 1; i < nums.size(); ++i){
if(nums[i] > nums[0] && minv > nums[i]){
id = i;
minv = nums[i];
}
}
if(id != -1){
swap(nums[0], nums[id]);
sort(nums.begin()+1, nums.end());
return;
}
sort(nums.begin(), nums.end());
}
};
结果:
