Note: This article is available in Chinese only. 本文暂无英文版本。
View original
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
思路: 参考了wiki_Permutation
有一个算法完美解决了这个问题,空间复杂度O(1),时间复杂度O(n)
The following algorithm generates the next permutation lexicographically after a given permutation. It changes the given permutation in-place.
- Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.
- Find the largest index l greater than k such that a[k] < a[l].
- Swap the value of a[k] with that of a[l].
- Reverse the sequence from a[k + 1] up to and including the final element a[n].
1/* ***********************************************
2Author :111qqz
3Created Time :2017年04月13日 星期四 14时39分33秒
4File Name :31.cpp
5************************************************ */
6class Solution {
7
8public:
9
10 void nextPermutation(vector<int>& nums) {
11
12 int n = nums.size();
13 if (n==0) return;
14 int k = -1;
15 for (int i = n-2 ; i>= 0 ; i--)
16 if (nums[i]<nums[i+1])
17 {
18 k = i;
19 break;
20 }
21 if (k==-1)
22 {
23 reverse(nums.begin(),nums.end());
24 return;
25 }
26 int l = -1;
27 for ( int i = n-1 ; i > k ; i--)
28 {
29 if (nums[k]<nums[i])
30 {
31 l = i;
32 break;
33 }
34 }
35 swap(nums[l],nums[k]);
36 reverse(nums.begin()+k+1,nums.end());
37
38 }
39
40};