首页 > 其他 > 详细

[LeetCode] Permutations II

时间:2014-03-20 18:02:24      阅读:420      评论:0      收藏:0      [点我收藏+]

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位的元素在枚举过程中需要判断是否已经出现过。

bubuko.com,布布扣
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;
    }
};
bubuko.com,布布扣

[LeetCode] Permutations II,布布扣,bubuko.com

[LeetCode] Permutations II

原文:http://www.cnblogs.com/changchengxiao/p/3613188.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!