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

LeetCode OJ--Permutations II

时间:2014-06-13 17:53:39      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

给的一个数列中,可能存在重复的数,比如 1 1  2 ,求其全排列。

记录上一个得出来的排列,看这个排列和上一个是否相同。

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

       vector<int> _num = num;
       sort(_num.begin(),_num.end());

       vector<int> _beforeOne = _num;
       ans.push_back(_num);
       while(nextPermutation(_num))
       {
           if(_num != _beforeOne)
           {
               ans.push_back(_num);
               _beforeOne = _num;
           }
       }
       return ans;
    }
private:
    bool nextPermutation(vector<int> &num)
    {
        return next_permutation(num.begin(),num.end());
    }

    template<typename BidiIt>
    bool next_permutation(BidiIt first,BidiIt last)
    {
        const auto rfirst = reverse_iterator<BidiIt>(last);
        const auto rlast = reverse_iterator<BidiIt>(first);

        auto pivot = next(rfirst);
        while(pivot != rlast && *pivot >= *prev(pivot))
        {
            ++pivot;
        }
        
        //this is the last permute, or the next is the same as the begin one
        if(pivot == rlast)
        {
            reverse(rfirst,rlast);
            return false;
        }
        //find the first num great than pivot
        auto change = rfirst;
        while(*change<=*pivot)
            ++change;

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

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

 

LeetCode OJ--Permutations II,布布扣,bubuko.com

LeetCode OJ--Permutations II

标签:style   class   blog   code   java   http   

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

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