题目
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> &num) {
int len=num.size();
if(len<=1)
return;
int i,j;
for(i=len-2;i>=0;i--) //扫描需要交换的高位
{
for(j=len-1;j>i;j--) //扫描需要交换的低位
{
if(num[j]>num[i])
{
swap(num[i],num[j]);
sort(num.begin()+i+1,num.end());
return;
}
}
}
sort(num.begin(),num.end());
}
};