31. Next Permutation
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
分析
求已知排列的下一个排列
举例:
[3,5,9,7,6,1]
下一个排列算法如下:
1. 从尾部1,向前找。找到首个不是递增的数字,这里是5。
2. 然后重新再尾部找到比5大的首个元素,这里是6。
3. 交换两个元素,[3,6,9,7,5,1],然后把后面下划线的元素倒序,[3,6,1,5,7,9],即为所求
4. 如果序列一直是从尾向头递增的,那么直接将整个序列反序,即为所求
算法复杂度,两次扫描分别 O(n),反序操作O(n/2),所以算法总的时间复杂度O(n)。 空间复杂度O(1)。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | class Solution { public : void nextPermutation(vector< int >& nums) { int len = nums.size(); if (len <= 1) return ; int last = INT_MIN, l_i = 0, b_i = 0; int i; for (i = len - 1; i >= 0; --i){ if ( last <= nums[i]){ last = nums[i]; l_i = i; } else { break ; } } // if i is -1, then reverse the whole vector if (i == -1){ reverse(nums, 0, nums.size()); return ; } // find the first element bigger than the target element for (i = len-1; i >= 0; --i){ if (nums[i] > nums[l_i-1]){ b_i = i; break ; } } swap(nums[l_i-1], nums[b_i]); reverse(nums, l_i, len); } // [start, end) // [...start, start+1, ...i, i+1,...,end-1] void reverse(vector< int > & nums, int start, int end){ for ( int i = start; i < start + (end-start)/2; ++i){ int temp = nums[i]; nums[i] = nums[end + start -1 - i]; nums[end + start -1 - i] = temp; } } }; |
leetcode discussion 简短代码
该代码思路相同,使用了库函数,更加简洁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Solution { public : void nextPermutation(vector< int > &num) { if (num.empty()) return ; // in reverse order, find the first number which is in increasing trend (we call it violated number here) int i; for (i = num.size()-2; i >= 0; --i) { if (num[i] < num[i+1]) break ; } // reverse all the numbers after violated number reverse(begin(num)+i+1, end(num)); // if violated number not found, because we have reversed the whole array, then we are done! if (i == -1) return ; // else binary search find the first number larger than the violated number auto itr = upper_bound(begin(num)+i+1, end(num), num[i]); // swap them, done! swap(num[i], *itr); } }; |