现在的位置: 首页 > 综合 > 正文

LeetCode: Subsets

2014年02月27日 ⁄ 综合 ⁄ 共 732字 ⁄ 字号 评论关闭

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

无重复数的全组合。

class Solution {
public:
    void comb(vector<int> &S, vector<vector<int> > &result, 
              vector<int> &tmp, int size, int n, int pos)
    {
        vector<int> v;
        for (int i = 0; i < n; ++i)
            v.push_back(tmp[i]);
        result.push_back(v);
        
        for (int i = pos; i < size; ++i)
        {
            tmp[n] = S[i];
            comb(S, result, tmp, size, n+1, i+1);
        }
    }
    
    vector<vector<int> > subsets(vector<int> &S) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int> > result;
        int nSize = S.size();
        sort(S.begin(), S.end());
        
        vector<int> tmp(nSize);
        comb(S, result, tmp, nSize, 0, 0);
        return result;
    }
};

抱歉!评论已关闭.