题目描述:

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

解题思路:

本题的解题重点在于从后面找到递增的数,然后再从后面找到一个比这个数大的数交换位置,再将该数后面的数反转。

代码:

 1 class Solution {
 2 public:
 3     void nextPermutation(vector<int>& nums) {
 4         int index = nums.size()-1;
 5         while(nums[index]<=nums[index-1] && index>1)
 6             index--;
 7         for(int i = nums.size()-1; i >= index-1; i--){
 8             if(nums[i] > nums[index-1]){
 9                 swap(nums[index-1],nums[i]);
10                 break;
11             }
12         }
13         reverse(nums.begin()+index, nums.end());
14     }
15 };

 

 

 

posted on 2018-02-27 00:37  宵夜在哪  阅读(97)  评论(0编辑  收藏  举报