码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Subsets

时间:2015-04-07 21:38:13      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

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],
  []
]
题意:求数组子集。

思路:一个dfs,取与不取;一个是二进制可以代表所有的子集。

class Solution {
public:
    vector<vector<int> > ans; 
    void subCal(vector<int> &S, int cur, vector<int> v) {
        if (cur == S.size()) {
            ans.push_back(v);
            return;
        }

        subCal(S, cur+1, v);
        v.push_back(S[cur]);
        subCal(S, cur+1, v);
    }

    vector<vector<int> > subsets(vector<int> &S) {
        vector<int> v;
        sort(S.begin(), S.end());
        subCal(S, 0, v);
        return ans;
    }
};


class Solution {
public:
    vector<vector<int> > subsets(vector<int> &S) {
        sort(S.begin(), S.end());
        int n = S.size();
        int Max = 1<<n;
        vector<vector<int> > ans;
        for (int i = 0; i < Max; i++) {
            vector<int> tmp;
            int cur = i;
            int indx = 0;
            while (cur > 0) {
                if (cur & 1) 
                    tmp.push_back(S[indx]);
                indx++;
                cur = cur >> 1;
            }
            ans.push_back(tmp);
        }

        return ans;
    }
};


LeetCode Subsets

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/44925791

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!