Description
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 and use only constant 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
Solution 1(C++)
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int i = nums.size() - 1, k = i;
while (i > 0 && nums[i-1] >= nums[i])
i--;
for (int j=i; j<k; j++, k--)
swap(nums[j], nums[k]);
if (i > 0) {
k = i--;
while (nums[k] <= nums[i])
k++;
swap(nums[i], nums[k]);
}
}
};
Solution 2(C++)
class Solution {
public:
void nextPermutation(vector<int>& nums) {
next_permutation(begin(nums), end(nums));
}
};
Solution 3(C++)
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int len=nums.size()-1;
int left=len, right=len;
while(nums[left]<=nums[left-1] && left>0) left--;
if(left==0) {reverse(nums.begin(), nums.end()); return;}
while(nums[right]<=nums[left-1] && right>0) right--;
swap(nums[left-1], nums[right]);
reverse(nums.begin()+left, nums.end());
}
};
算法分析
解法二我就不多说了,居然有直接的函数。主要说一下解法三。
这一道题的模型其实是,一堆元素构成的数列,元素不同的排列,元素构成的数列对应的数大小也会发生改变。我们先就来研究一下这个规律。
- 一组元素,按照不递减的顺序从前往后排列,从后往前看就是不递增,那么组成的数最小;
- 一组元素,按照不递增的顺序从前往后排列,从后往前看就是不递减,那么组成的数最大。
这是第一个规律,很简单。例如:
[1,2,3,4,5,6]
[6,5,4,3,2,1]
那么现在在[6,5,4,3,2,1]这一组元素的左边,新加一个元素:3,那么新构成的数列能组成的最接近当前数列的数:3654321的数列是多少呢?
[4,1,2,3,3,5,6]
因为3作为最高位,比他低的位上的数字构成的数已经是最大的了,要想比他更大,只能改变最高位。而又不能大太多,只能大一点,那么最高位只能换成4,然后除掉4以外,余下元素应该组成最小的数,满足从前往后不递减顺序排列。
以上过程,就足以解决这道题目了。可以参考:LeetCode-31. Next Permutation-Approach #2 Single Pass Approach [Accepted]中的动态图解释。很形象。
这道题对理解这种数列元素排序组成的数很有帮助。
程序分析
略。