Next Permutation 寻找下一个排列数
原创
©著作权归作者所有:来自51CTO博客作者我想有个名字的原创作品,请联系作者获取转载授权,否则将追究法律责任
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
class Solution {
public:
void nextPermutation(vector<int> &num) {
// 1 3 2 3 2 1
// 1 3 3 2 1 2
//1 从后向前扫描,找到一对为升序的相邻元素,记为i和j(i < j)。如果不存在这样一对为升序的相邻元素,则所有排列均已找到,算法结束;
//2 否则,重新对当前排列从后向前扫描,找到第一个大于i的元素k,交换i和k,然后对从j开始到结束的子序列反转,
int i,j,len=num.size();
if (len<2){
return ;
}
for(i=len-2;i>=0;i--)
{
if(num[i]<num[i+1])
break;
}
if(i==-1)
{
reverse(num.begin(),num.end());
}
else{
for(j=len-1;j>i;j--)
{
if(num[j]>num[i])
break;
}
swap(num[i],num[j]);
reverse(num.begin()+i+1,num.end());
}
}
};