31. Next Permutation
Posted midhillzhou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了31. Next Permutation相关的知识,希望对你有一定的参考价值。
mplement 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
思考:以1,3,2,5,4,3,1为例,从右向左,直到5依次递增,说明,相对大的数都已经放在相对大的权重,已经达到最大。再向左观察2,考察2,5,4,3,1。显然2这个位置可以放更大的数字以实现数的变大,找到2右边的最靠近2的比2大的数,3。所以应该是3代替2的位置,然后后面的这4个位置的数应该尽可能的小,即最大的数字在最低位,降序即可。
1 class Solution { 2 public: 3 void nextPermutation(vector<int>& nums) { 4 5 int len = nums.size(); 6 int index = len-2; 7 while(index>=0 && nums[index]>=nums[index+1]) index--; 8 9 if(index==-1) {sort(nums.begin(),nums.end()); return;} 10 11 int index2 = len-1; 12 while(nums[index2]<=nums[index]) index2--; 13 14 swap(nums[index], nums[index2]); 15 16 sort(nums.begin()+index+1,nums.end()); 17 18 19 } 20 };
以上是关于31. Next Permutation的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode - 31. Next Permutation
LeetCode OJ 31. Next Permutation
LeetCode31 Next Permutation and LeetCode60 Permutation Sequence