78. Subsets

Given a set of distinct integers, nums, 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 nums = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

class Solution {
public:
    void dfs(vector<vector<int>>&u,int x,vector<int>& nums,vector<int>&v,int cnt,int n){
        if(cnt==n){
            //n++;
            u.push_back(v);
            return ;
        }
        for(int i=x;i<nums.size();i++){
            v.push_back(nums[i]);
            dfs(u,i+1,nums,v,cnt+1,n);
            v.pop_back();
        }    
    }
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>>u; 
        vector<int>v;
        sort(nums.begin(),nums.end());
        for(int i=0;i<=nums.size();i++){
            dfs(u,0,nums,v,0,i);
        }
        return u;
    }
};

 

posted on 2016-04-05 18:22  Beserious  阅读(171)  评论(0编辑  收藏  举报