码迷,mamicode.com
首页 > 其他好文 > 详细

31. Next Permutation

时间:2018-05-04 18:26:57      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:gem   only   phi   replace   ons   ati   get   bsp   wiki   

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,31,3,2
3,2,11,2,3
1,1,51,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

标签:gem   only   phi   replace   ons   ati   get   bsp   wiki   

原文地址:https://www.cnblogs.com/midhillzhou/p/8991688.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!