Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.spa
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).code
The replacement must be in-place, do not allocate extra memory.blog
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
it
感受又是一道智商题啊,方法比较难以想到,想到后就容易了,没有本身写代码,直接看的网上的答案·················································io
题意寻找比当前排列顺序大的下一个排列。class
1)由于降序序列是无法变的更大的,因此从后往前找到第一个升序对的位置。方法
2)而后就存在调整大小排列顺序的可能,从后往前找到比当前位置大的元素,交换之。call
3)当前位置后面的元素仍是降序排列,将他们反转获得最小顺序排列。其实就是原来当前位置元素后面是最大的排列,而交换后的新元素以后是最小的排列,他们就是相邻的顺序。next
当不存在升序,则当前排列是最大排列,只要旋转整个序列变成最小排列。 sort
class Solution { public: void nextPermutation(vector<int>& nums) { int i,j,len=num.size(); for(i=len-2;i>=0;--i) { if(num[i+1]>num[i]) { for(j=len-1;j>i-1;--j)if(num[j]>num[i])break; swap(num[i],num[j]); reverse(num.begin()+i+1,num.end()); return; } } reverse(num.begin(),num.end()); return; } };