首页 > 其他 > 详细

leetcode | Next Permutation

时间:2015-05-29 18:15:26      阅读:303      评论:0      收藏:0      [点我收藏+]

问题

Next Permutation:https://leetcode.com/problems/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


解析

首先需要理解题目的意思:

rearranges 重新排列;permutation 排列;ascending order 升序

求当前排列的下一个排列:
所谓一个排列的下一个排列的意思就是 这一个排列与下一个排列之间没有其他的排列。
这就要求这一个排列与下一个排列有尽可能长的共同前缀,也即变化限制在尽可能短的后缀上。

  1. 初始化 k = nums.size()-1
  2. 首先从左到右找到第一个满足 nums[k] < nums[k-1] 的k值,保证得到当前排列的后面序列
  3. 找到 nums 在 k ~ end 中大于nums[k-1]的最小值
  4. 交换nums[k-1] 和 第二步中的值
  5. 按从小到大的顺序,对nums 中从k 到 end 排序
    技术分享
    上述图片来自https://github.com/soulmachine/leetcode

代码实现

//rearranges 重新排列;permutation 排列;ascending order 升序
//所谓一个排列的下一个排列的意思就是 这一个排列与下一个排列之间没有其他的排列。
//这就要求这一个排列与下一个排列有尽可能长的共同前缀,也即变化限制在尽可能短的后缀上。
// 最差时间复杂度 O(n^2) 空间复杂度 0
class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        if (nums.size() == 0)
            return;
        int k = nums.size()-1;
        int last = k;
        while (k) {
            if (nums[k-1] < nums[k]) {
                while (nums[k-1] >= nums[last]) {
                    last--;  //从后往前找(也可从前往后)
                }
                swap(nums[k-1], nums[last]);
                break;
            } else {
                k--;
            }
        }
        sort(nums.begin()+k, nums.end());
    }
 private:
    void swap(int &a, int &b) {
        int t = a;
        a = b;
        b = t;
    }
};

leetcode | Next Permutation

原文:http://blog.csdn.net/quzhongxin/article/details/46237151

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!