[LeetCode] 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].

Solution:


由于数据中有重复,在递归时需要判断是否可以交换。基本的枚举思路是每个数分别出现在第k位,然后排列剩下的元素。这里第k位的元素在枚举过程中需要判断是否已经出现过。

class Solution {
public:
    vector<vector<int> > ans;
    vector<int> src;
    int srcLen;
    
    void perm(int i)
    {
        if(i == srcLen - 1)
        {
            vector<int> tmp;
            for(int i = 0;i < srcLen;i++)
                tmp.push_back(src[i]);
            ans.push_back(tmp);
        }
        else
        {
            set<int> dic;
            for(int k = i;k < srcLen;k++)
            {
                if(dic.find(src[k]) == dic.end())
                {
                    int t = src[i];
                    src[i] = src[k];
                    src[k] = t;
                    perm(i + 1);
                    src[k] = src[i];
                    src[i] = t;
                    dic.insert(src[k]);
                }
            }
        }
    }
    
    vector<vector<int> > permuteUnique(vector<int> &num) {
        src = num;
        srcLen = num.size();
        perm(0);
        return ans;
    }
};

 

posted @ 2014-03-20 11:00  xchangcheng  阅读(213)  评论(0编辑  收藏  举报