Tuesday, October 21, 2014

Permutations II

class Solution {
public:
    vector<vector<int> > permuteUnique(vector<int> &num) {
        vector<vector<int> >res;
        vector<int> com;
        vector<bool> used(num.size(),false);
        sort(num.begin(),num.end());
        permuteRe(num,used,com,res);
        return res;
       
    }
    void permuteRe(vector<int> &num,vector<bool> &used,vector<int>& com,vector<vector<int> >&res){
        if(com.size()==num.size()){
            res.push_back(com);
            return;
        }
        for(int i=0;i<num.size();i++){
            if(used[i] || (i>0&&num[i]==num[i-1]&&!used[i-1])) continue;
            used[i]=true;
            com.push_back(num[i]);
            permuteRe(num,used,com,res);
            com.pop_back();
            used[i]=false;
        }
    }
};

No comments:

Post a Comment