LeetCode Subsets

来源:互联网 发布:苹果ipowerl软件 编辑:程序博客网 时间:2024/05/21 21:34

题目:

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());int n = S.size();vector<int> row;ans.clear();dfs(0, row, n, S);return ans;}private:    vector<vector<int>> ans;    //每个元素有取和不取两种选择,使用深度搜索,共2^n(n为集合大小)个子集void dfs(int depth, vector<int> row, int n, vector<int> &S) {if (depth == n) {ans.push_back(row);return;}dfs(depth + 1, row, n, S);row.push_back(S[depth]);dfs(depth + 1, row, n, S);}};


0 0
原创粉丝点击