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
题意寻找比当前排列顺序大的下一个排列。
因为降序序列是没法变的更大的,所以从后往前找到第一个升序对的位置。
然后就存在调整大小排列顺序的可能,从后往前找到比当前位置大的元素,交换之。
当前位置后面的元素还是降序排列,将他们反转得到最小顺序排列。其实就是原来当前位置元素后面是最大的排列,而交换后的新元素之后是最小的排列,他们就是相邻的顺序。
当不存在升序,则当前排列是最大排列,只要旋转整个序列变成最小排列.
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int i,j;
int n = nums.size();
for(i = n-2; i >= 0; i--)
{
if(nums[i+1]>nums[i])//找到升序的第一个位置
{
for(j = n-1; j > i-1; j--)
if(nums[j]>nums[i])//因为后面都是降序的,找到第一个比当前元素大的数,这个数也就是比它大的数里面最小的数
break;
swap(nums[i], nums[j]);//交换位置,交换后后面的序列仍然是降序的
reverse(nums.begin()+i+1, nums.end());//后面的序列反转变成升序的
return ;
}
}
reverse(nums.begin(), nums.end());//如果没有升序的,也就是完全降序的那么直接反转
return ;
}
};