Permutations II

 Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].

class Solution {
public:
    vector<vector<int> > ans;
    void dfs(vector<int> &num,vector<int> &path){
        if (path.size() == num.size()){
            ans.push_back(path);
            return;
        }
        for(int j = 0; j < num.size(); j++){
            if (j && num[j] == num[j -1]){
                continue;
            }
            int c1 = 0, c2 = 0;
            for(int k = 0; k < num.size(); k++){
                if (num[k] == num[j]){
                    c1++;
                }
                if (num[k] > num[j]){
                    break;
                }
            }
            for(int i = 0; i < path.size(); i++){
                if (path[i] == num[j]){
                    c2++;
                }
            }
            if (c2 >= c1){
                continue;
            }
            path.push_back(num[j]);
            dfs(num,path);
            path.resize(path.size() -1);
        }
        
    }
    vector<vector<int> > permuteUnique(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        ans.clear();
        vector<int> path;
        sort(num.begin(),num.end());
        dfs(num,path);
        return ans;
    }
};

 

posted @ 2013-07-12 08:42  一只会思考的猪  阅读(139)  评论(0编辑  收藏  举报