首页 > 其他 > 详细

47. Permutations II (Recursion, DP)

时间:2015-10-05 08:09:03      阅读:257      评论: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].

思路:有重复数字的情况,之前在Subsets II,我们采取的是在某一个递归内,用for循环处理所有重复数字。这里当然可以将数组排序,然后使用该方法。

而另一种方法是不排序,在一个递归内申请一个set,用来判断该数字是否已经在当前depth出现过。

class Solution {
public:
    vector<vector<int> > permuteUnique(vector<int> &num) {
        result.clear();  
        sort(num.begin(),num.end());
        dfs(num, 0);
        return result;
    }
    void dfs(vector<int> num, int depth)
    {
        if(depth == num.size()-1)
        {
            result.push_back(num);
            return;
        }
        
        dfs(num,depth+1);
        set<int> flag; //用来判断当前数字是否在depth位置出现过
        flag.insert(num[depth]);
        int temp = num[depth];
        for(int i = depth+1; i< num.size(); i++)
        {
           if(flag.find(num[i])!=flag.end()) continue;
           flag.insert(num[i]);
           num[depth]=num[i];
           num[i] = temp;
           dfs(num,depth+1);
           num[i]=num[depth];
           num[depth]=num[i];
        }
    }
private:
    vector<vector<int> >  result;
};

 

47. Permutations II (Recursion, DP)

原文:http://www.cnblogs.com/qionglouyuyu/p/4855305.html

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