04月23日, 2016 1,912 views次
Link
Problem
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
Mean
给定一个vector,求下一个排列。
Analysis
可以直接使用STL的next_permutation函数,其原理为:
在当前序列中,从尾端向前寻找两个相邻元素,前一个记为*i,后一个记为*t,并且满足*i < *t。然后再从尾端寻找另一个元素*j,如果满足*i < *j,即将第i个元素与第j个元素对调,并将第t个元素之后(包括t)的所有元素颠倒排序,即求出下一个序列了。
详细写法见代码
Code1
class Solution { public: void nextPermutation(vector<int>& nums) { next_permutation(nums.begin(), nums.end()); } };
Code2
class Solution { public: void nextPermutation(vector<int>& v) { int i = v.size()-2; for(; i >= 0; --i) { if(v[i] < v[i+1]) { for(int j = v.size()-1; j > i; --j) { if(v[i] < v[j]) { swap(v[j], v[i]); break; } } reverse(v.begin() + i + 1, v.end()); break; } } if(i < 0) { reverse(v.begin(), v.end()); } } };