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

LeetCode OJ:Next Permutation(下一排列)

时间:2015-10-30 12:06:26      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

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

 

LeetCode OJ:Next Permutation(下一排列)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4922649.html

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