• leetcode Subsets


    Given a set of distinct integers, 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,3], a solution is:

    [
      [3],
      [1],
      [2],
      [1,2,3],
      [1,3],
      [2,3],
      [1,2],
      []
    ]
    

     深搜即可

     如果想更加深入的理解集合的子集问题可以阅读《Efficiently Enumerating the Subsets of a Set》

    typedef vector<vector<int> > VectorArray;
    vector<int> solution;
    VectorArray result;
    
    void  dfs(int k, vector<int>& S){
        for(int i = k; i < S.size(); ++ i){
            solution.push_back(S[i]);
            result.push_back(solution);
            dfs(i+1,S);
            solution.pop_back();
        }
    }
    VectorArray subsets(vector<int>& S){
        sort(S.begin(),S.end());
        result.push_back(solution);
        dfs(0,S);
        return result;
    }

     另一个比较简单的方法,根据集合生产规则,迭代生产,可以手动模拟一下{1,2,3}

    最初子集为{{}}

    添加一个元素后为{{},{1}},则在现有的集合上添加下一个元素,现有子集{},{1}

    添加元素2后为{2},{1,2},加入子集为{{},{1},{2},{1,2}},在现有的子集上添加集合

    添加元素3后为{3},{1,3},{2,3},{1,2,3},加入子集后

    得到

    {{},{1},{2},{3},{1,2},{1,3},{2,3},{1,2,3}}

    vector<vector<int> > subsets(vector<int>& S){
        vector< vector<int> > result;
        vector<int> empty;
        result.push_back( empty );
    
        for (int i = 0; i < set.size(); i++)
        {
            vector< vector<int> > subsetTemp = result;
    
            for (int j = 0; j < subsetTemp.size(); j++)
                subsetTemp[j].push_back( set[i] );
    
            for (int j = 0; j < subsetTemp.size(); j++)
                result.push_back( subsetTemp[j] );
        }
        return result;
    }

     还有一种方法是利用位实现集合,可以参考http://codeding.com/?article=12

    如果不能打开,可以参考下面一句话

    There will be 2N subsets for a given set, where N is the cardinality (number of items) of that set. For example, there will be 25 = 32 subsets for the set {1, 2, 3, 4, 5}. The binary representation of each number 'i' in the range 0 to (2N - 1) is used to find the corresponding ith subset.

    Each '1' in the binary representation indicates an item in that position. For example, the binary representation of number 5 is 00101 which in turn represents the subset {3, 5} of the set {1, 2, 3, 4, 5}.

  • 相关阅读:
    Redis 如何保证缓存与数据库双写时的数据一致性
    Redis 缓存雪崩和缓存穿透问题
    Redis 的并发竞争 Key 问题
    【转】intelliJ IDEA集成checkStyle
    【转】hadoop深入研究:(十一)——序列化与Writable实现
    【转】Hadoop在MapReduce中使用压缩详解
    【转】JDK工具jinfo用法详解
    【转】JVM统计监控工具-jstat
    【转】jps命令使用
    基于MLlib的机器学习--协同过滤与推荐
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3801574.html
Copyright © 2020-2023  润新知