Subsets,Subsets II

一.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<int>& nums ,int numsSize,int startPos,vector<vector<int>>& res,vector<int>& oneOfRes)
    {
        for(int i=startPos;i<numsSize;i++){
            oneOfRes.push_back(nums[i]);
            res.push_back(oneOfRes);
            dfs(nums,numsSize,i+1,res,oneOfRes);
            oneOfRes.pop_back();
        }
    }
    vector<vector<int>> subsets(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        vector<vector<int>> res;
        vector<int> oneOfRes;
        res.push_back(vector<int>());
        int numsSize = nums.size();
        dfs(nums,numsSize,0,res,oneOfRes);
        return res;
    }
};

 二.SubsetsII

Given a collection of integers that might contain duplicates, 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,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]
class Solution {
public:
    void dfs(vector<int>& nums,int numsSize,int startPos,vector<vector<int>>& res,vector<int>& oneOfRes)
    {
        for(int i=startPos;i<numsSize;i++){
            if(i>startPos && nums[i]==nums[i-1]){
                continue;
            }
            oneOfRes.push_back(nums[i]);
            res.push_back(oneOfRes);
            dfs(nums,numsSize,i+1,res,oneOfRes);
            oneOfRes.pop_back();
        }
    }
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        vector<vector<int>> res;
        vector<int> oneOfRes;
        int numsSize = nums.size();
        res.push_back(oneOfRes);
        dfs(nums,numsSize,0,res,oneOfRes);
        return res;
    }
};

 

posted @ 2015-12-06 22:22  zengzy  阅读(175)  评论(0编辑  收藏  举报
levels of contents