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

LeetCode OJ--Next Permutation *

时间:2014-06-13 16:41:56      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

求一个排列的下一个排列。

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

bubuko.com,布布扣
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
 
class Solution{
public:
    void nextPermutation(vector<int> &num) {
        if(num.size() == 0)
            return;

        const vector<int>::reverse_iterator rfirst= num.rbegin();
        const vector<int>::reverse_iterator rend = num.rend();

        auto pivot = next(rfirst);
        while(pivot != rend && *pivot >= *prev(pivot))
        {
            ++pivot;
        }
        
        if(pivot == rend)
        {
            reverse(rfirst,rend);
            return;
        }
        //find the first num great than pivot
        auto change = rfirst;
        while(*change<=*pivot)
            ++change;

        swap(*change,*pivot);
        reverse(rfirst,pivot);
        return;
    }
};

int main()
{
    vector<int> num;
    num.push_back(1);
    num.push_back(1);
    num.push_back(5);
     
    Solution myS;
    myS.nextPermutation(num);
    return 0;
}
bubuko.com,布布扣

 

LeetCode OJ--Next Permutation *,布布扣,bubuko.com

LeetCode OJ--Next Permutation *

标签:style   class   blog   code   java   http   

原文地址:http://www.cnblogs.com/qingcheng/p/3784586.html

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