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

 

转载于:https://www.cnblogs.com/-wang-cheng/p/4922649.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值