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,23,2,1 → 1,2,31,1,5 → 1,5,1
本题是给了左边的一个排列,给出它的下一个排列。下一个排列是指按词典序的下一个排列。降序的排列已经是按词典序的最大的排列了,所以它的下一个就按升序排列。
class Solution { public: void nextPermutation(vector<int> &num) { int end = num.size() - 1; int povit = end; while (povit){ if (num[povit] > num[povit-1]) break; povit--; } if (povit > 0){ povit--; int large = end; while (num[large] <= num[povit]) large--; swap(num[large], num[povit]); reverse(num.begin() + povit + 1, num.end()); } else reverse(num.begin(), num.end()); } };
[LeetCode] #31 Next Permutation
原文:http://www.cnblogs.com/Scorpio989/p/4576639.html