LeetCode算法题目: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


分析:

字典序法就是按照字典排序的思想逐一产生所有排列。
例如,由1,2,3,4组成的所有排列,从小到大的依次为:

1234, 1243, 1324, 1342, 1423, 1432,
2134, 2143, 2314, 2341, 2413, 2431,
3124, 3142, 3214, 3241, 3412, 3421,
4123, 4132, 4213, 4231, 4312, 4321.

分析这种过程,看后一个排列与前一个排列之间有什么关系?
再如,设有排列(p)=2763541,按照字典式排序,它的下一个排列是什么?
276 35 41 (找最后一个正序35)
27635 4 1 (找3后面比3大的最后一个数4)
276 4 5 3 1 (交换3,4的位置)
2764 135 (把4后面的5,3,1反转)
下面给出求 p[1…n] 的下一个排列的描述:

  1. 求 i = max{j | p[j – 1] < p[j]} (找最后一个正序)
  2. 求 j = max{k| p[i – 1] < p[k]} (找最后大于 p[i – 1] 的)
  3. 交换 p[i – 1] 与 p[j]得到 p[1] … p[i-2] p[j] p[i] p[i+1] … p[j-1] p[i-1] p[j+1] … p[n]
  4. 反转 p[j] 后面的数得到 p[1] … p[i-2] p[j] p[n] … p[j+1] p[i-1] p[j-1] … p[i]


代码:

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int i,j;
        int length= nums.size();
        for (i=length-2;i>=0;i--)
        {
            if(nums[i+1]>nums[i])
            {
                for(j=length-1;j>=0;j--)
                {
                    if(nums[j]>nums[i])
                    break;
                }
                swap(nums[i],nums[j]);
                reverse(nums.begin()+i+1,nums.end());
                return;
            }
        }
        reverse(nums.begin(),nums.end());
        return;
    }
};
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值