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 n = num.size(); if(n == 1)return; for(int i = n-2, ii = n-1; i >= 0; i--,ii--) if(num[i] < num[ii]) { int j = n-1; while(num[j] <= num[i])j--;//从尾部找到第一个比num[i]大的数,一定可以找到 swap(num[i], num[j]); reverse(num.begin()+ii, num.end()); return; } reverse(num.begin(), num.end()); } };
STL中还提供了一个prev_permutation,可以参考我的另一篇博客:here
【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3770126.html