LeetCode OJ:Next Permutation(下一排列)

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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1


求下一排列,由于递减序列就没有下一排列了,那么从右往左找第一个递减序列(就是从左向右的递增的),找到这两个数之后,从右往左找第一个大于这个数的数,交换这两个数之后,再将原来的递减序列(从右向左递增)reverse之后就得到下一排列了。这题本来没写出来,看了别人的实现,代码如下所示:

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

 

posted @ 2015-10-30 10:45  eversliver  阅读(204)  评论(0编辑  收藏  举报