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

LeetCode:Next Permutation

时间:2014-06-07 11:10:30      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:c   class   blog   code   a   http   

题目链接

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,31,3,2
3,2,11,2,3
1,1,51,5,1


步骤如下:

  • 从最尾端开始往前寻找两个相邻的元素,两者满足i < ii(令第一个元素为i,第二个元素为ii)
  • 如果没有找到这样的一对元素则,表明当前的排列是最大的,没有下一个大的排列
  • 如果找到,再从末尾开始找出第一个大于i的元素,记为j                                  本文地址
  • 交换元素i, j,再将ii后面的所有元素颠倒排列(包括ii)
  • 如果某个排列没有比他大的下一个排列(即该排列是递减有序的),调用这个函数还是会把原排列翻转,即得到最小的排列
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
    void nextPermutation(vector<int> &num) {
        int n = num.size();
        if(n == 1)return;
        for(int i = n-2, ii = n-1; i >= 0; i--,ii--)
            if(num[i] < num[ii])
            {
                int j = n-1;
                while(num[j] <= num[i])j--;//从尾部找到第一个比num[i]大的数,一定可以找到
                swap(num[i], num[j]);
                reverse(num.begin()+ii, num.end());
                return;
            }
        reverse(num.begin(), num.end());
    }
};

 

STL中还提供了一个prev_permutation,可以参考我的另一篇博客:here

 

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3770126.html

LeetCode:Next Permutation,布布扣,bubuko.com

LeetCode:Next Permutation

标签:c   class   blog   code   a   http   

原文地址:http://www.cnblogs.com/TenosDoIt/p/3770126.html

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