问题: 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
方法
permutation
例如已给数字[1,2,3],所有排序序列如下(字典升序):```cpp { [1,2,3] [1,3,2] [2,1,3] [2,3,1] [3,1,2] [3,2,1] }<br />题目中要求`Next permutation`,即给定已有的一组排序序列,求下一组排序序列。```cpp # 例如 # [1,2,3] -> [1,3,2] # [2,3,1] -> [3,1,2]由以上排列组合的过程可以看出,若是将一组序列分割为两部分,那么求下一组序列的过程就可以类似于数字加和进位的过程。
- 将一组序列分割成两部分之后,第二部分的序列总是降序排列的(从左到右)
由此可以总结出算法过程:
```cpp
//时间复杂度O(n),空间复杂度O(1)
void next_permutation(vector&nums) { int length = nums.size(); // From right to left, find the first digit(partitionNumber) // which violates the increase trend int p = length - 2; while (p > -1 && nums[p] >= nums[p + 1]) —p; // If not found, which means current sequence is already the largest // permutation, then rearrange to the first permutation and return false if (p == -1) {
reverse(nums.begin(),nums.end()); return;}
// From right to left, find the first digit which is greater // than the partition number, call it changeNumber int c = length - 1; while (c > 0 && nums[c] <= nums[p]) —c;
// Swap the partitionNumber and changeNumber swap(nums[p], nums[c]); // Reverse all the digits on the right of partitionNumber reverse(nums.begin()+p+1,nums.end()); } ```
