Next Permutation
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
【解法】
step1:从它的最后一个元素开始,向从后向前遍历,找到第一个满足nums[index] < nums[index+1]的索引index。因此,从nums[index+1, n-1]的元素是反向排序的。
(例如原始号码135421,nums[index] = 3,nums[index+1, n-1] 值为5421,是反向排序。)
step2:为了找到下一个排列,我们必须增大nums[index]的值,同时为了使增加的量最小化,将它与num[index+1, n-1]之间的大于nums[index]的最小值交换。
(nums[index] = 3,nums[index+1, n-1]之间的大于nums[index]的最小值是4,所以交换这两个数字,变为145321。)
step3:最后一步是使num[index+1, n-1]尽可能小,我们只需要逆向排序num[index+1, n-1]。
(num[index+1, n-1]为5321,对其进行逆向排序,为1235,所以最终结果为141235。)
class Solution {
public:
void nextPermutation(vector<int>& nums) {
if(nums.size()<=1)
return;
int index;
for(index=nums.size()-2; index>=0; --index){
if(nums[index]<nums[index+1])
break;
}
// 当输入为321时,index此时为-1
if(index>=0){
int i = nums.size()-1;
while(nums[i]<=nums[index])
--i;
swap(nums[index], nums[i]);
}
reverse(nums.begin()+index+1, nums.end());
}
};