zoukankan      html  css  js  c++  java
  • [leetcode] Subsets II

    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],
      []
    ]

    思路:

    Subsets一样,只是这里原容器中有重复的元素,于是就增加一个去重。去重的方法我用的还是与leetcode上的另一个题目一样,开辟一个数组记录当前元素是否使用过。如果当前元素等于前一个元素,且前一个元素没有使用,那么当前元素就不能使用。

    class Solution {
    public:
        vector<vector<int> > res;
        void dfs(vector<int> &s, bool used[], int index, vector<int> tmp) {
            if(index==s.size()) {
                res.push_back(tmp);
                return;
            }
            dfs(s, used, index+1, tmp);
            if(!used[index]) {
                if(index!=0 && s[index]==s[index-1] && !used[index-1])
                    return;
                used[index] = true;
                tmp.push_back(s[index]);
                dfs(s, used, index+1, tmp);
                used[index] = false;
            }
        }
        vector<vector<int> > subsetsWithDup(vector<int> &s) {
            sort(s.begin(), s.end());
            vector<int> tmp;
            int n = s.size();
            bool *used = new bool [n];
            memset(used, false, n);
            dfs(s, used, 0, tmp);
            return res;
        }
    };
    View Code

     

  • 相关阅读:
    sql 计算auc
    tf.app.flags
    transformer
    python 直连 hive
    rnn 详解
    yolov3
    记学习react-native
    html5横、竖屏状态 以及禁止横屏
    图片懒加载
    npm安装的时候报-4048
  • 原文地址:https://www.cnblogs.com/jiasaidongqi/p/4206784.html
Copyright © 2011-2022 走看看