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

 

Thinking: Take 1, 3, 2, 5, 4, 3, 1 as an example, increasing from right to left until 5, indicating that relatively large numbers have been placed in relatively large weights and have reached the maximum. Then look to the left 2, examine 2,5,4,3,1. Obviously, a larger number can be placed in the position of 2 to achieve a larger number. Find the number that is closest to 2 to the right of 2 and larger than 2, 3. Therefore, it should be 3 instead of 2, and then the numbers in the following 4 positions should be as small as possible, that is, the largest number is in the lowest position, and the descending order can be done.

 

 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 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325298463&siteId=291194637