zoukankan      html  css  js  c++  java
  • LeetCode:Subsets II

    Given a collection of integers that might contain duplicates,S, return all possible subsets.


    Note:


    • Elements in a subset must be in non-descending order.
    • The solution set must not contain duplicate subsets.


    For example,


    If S =[1,2,2], a solution is:

    [
      [2],
      [1],
      [1,2,2],
      [2,2],
      [1,2],
      []
    ]
    
    解题思路:
        
        思路跟Subset i一样,只是这里须要特别处理一下的是集合中存在反复元素的情况.
    
    
    我们先来看下例子的状态树:
    
    
    
    
    
    
        从上面图中,我们能够发现,从根到叶子节点即是所要求的集合的一个子集,但问题就在于
    
    
    某些从根到叶子节点的集合同样,而我们仅仅须要当中一个,那我们怎么去重?我们看下图中
    
    
    红色和蓝色标记的部分。从根到它们的父节点上的路径肯定是同样的,而因为第2号元素和第3号
    
    
    元素反复,导致了红色部分的右支和蓝色部分的左支结果同样,所以这样的情况里面,我们仅仅须要保留
    
    
    一种就可以.故这里仅仅须要引进一个bool变量,用于标记当前节点的右支是否须要进行搜索,就能去重了.
    
    
    解题代码:
    
    
    class Solution {
    public:
        void dfs(vector<int> &S, bool flag, int pos, vector<int> &path,vector<vector<int> > &res)
        {
            if (pos >= S.size())
            {
                res.push_back(vector<int>(path.begin(),path.end()));
                return;
             }
            dfs(S, pos + 1 < S.size() && S[pos] != S[pos+1], pos + 1, path, res);
            path.push_back(S[pos]);
            if (flag)
                dfs(S, true, pos + 1, path,res);
            path.pop_back();
        }
        vector<vector<int> > subsetsWithDup(vector<int> &S) 
        {
            sort(S.begin(),S.end());
            vector<vector<int> > res;
            vector<int> path;
            dfs(S,true,0,path,res);
            return res;
        }
    };
    


    
    
    
    
    
    
  • 相关阅读:
    C++对象模型与内存位对齐的简单分析(GNU GCC&VS2015编译器)
    [GeekBand] C++学习笔记(2)——BigThree、OOP
    [GeekBand] C++ 高级编程技术 (1)
    [GeekBand]C++高级编程技术(2)
    C++中引用的本质分析
    函数的重载(1)
    C++的特点
    布尔类型和三目运算符
    Linux客户端下的latex相关操作
    无光驱上网本上安装win7
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/6785509.html
Copyright © 2011-2022 走看看