论坛首页 编程语言技术论坛

[Leetcode] Subsets

浏览 1223 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-09-09  
SubsetsApr 18 '126226 / 16269

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:
    vector<vector<int> > subsets(vector<int> &S) {
        sort(S.begin(), S.end());
        vector<vector<int> > res;
        int n = S.size();
        for (int i = 0; i <= n; i++) {
            vector<int> a;
        	gen(res, S, i, 0, a);
        }
        return res;
    }

    void gen(vector<vector<int> >& res, const vector<int>& s, int n, int cur, vector<int> &a) {
    	if (a.size() == n) {
    		res.push_back(a);
    		return;
    	}
        if (cur == s.size()) return;

    	gen(res, s, n, cur+1, a);
    	
    	a.push_back(s[cur]);
    	gen(res, s, n, cur+1, a);
    	a.pop_back();
    }
};

 

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics