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

  DFS + 剪枝

复制代码
class Solution {
public:
   void DFS(vector<int> &num, int size,vector<int> temp)
    {
        if(size == n){
            result.push_back(temp);
            return ;
        }
        for(int i = 0; i< n; i++)
        {
            if(flag[i] || (i!= 0 &&flag[i-1] && num[i] == num[i-1] ) )
                  continue;
            
            temp[size] = num[i];
            flag[i] = true;
            DFS(num, size+1, temp);
            flag[i] = false;
           
        }
    }
    vector<vector<int> > permuteUnique(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        n = num.size();
        result.clear();
        
        
        sort(num.begin(), num.end());
        
        if(n == 0) return result;
        flag.resize(n,false);
        vector<int> temp(n,0) ;         
        DFS(num,0,temp);   
        
        return result ;
    }
private :
   int  n;
   vector<bool> flag;
   vector<vector<int>> result;   
};
复制代码

这里解释下剪枝的原理: 有重复元素的时候,因为重复的元素处理无序所以导致重复,所以只要给重复的元素进入temp定义一个次序就可以去掉重复。这里定义次序的规则是: 先对所有元素排序对于有重复的元素,必须是排在后面的元素比排在前面的元素先进入temp

重写后,貌似比第一个版本要快一点

class Solution {
public:
    void DFS(vector<int> &num, vector<int> &tp, vector<bool> flag)
    {
        if(num.size() == tp.size()){
            res.push_back(tp);
            return;
        }
        for(int i = 0; i< num.size(); i++)
        {
            if(flag[i] == true) continue;
            if(i != 0 && num[i] == num[i-1] && flag[i-1] == false) continue;
         
            flag[i] = true;
            tp.push_back(num[i]);
            DFS(num, tp, flag);
            tp.pop_back();
            flag[i] = false;
        }
    }
    vector<vector<int> > permuteUnique(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        res.clear();
        int len = num.size();
        if(len < 1) return res;
        sort(num.begin(), num.end());
        vector<bool> flag(len, false);
        vector<int> tp;
        DFS(num, tp, flag);
        return res;
         
    }
private:
    vector<vector<int>> res;
};

  

posted @   冰点猎手  阅读(289)  评论(0编辑  收藏  举报
编辑推荐:
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
阅读排行:
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· 为什么AI教师难以实现
· 如何让低于1B参数的小型语言模型实现 100% 的准确率
· AI Agent爆火后,MCP协议为什么如此重要!
点击右上角即可分享
微信分享提示