leetcode Subsets

OpenSoucre發表於2014-06-21

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

相關文章