关闭

leetcode #78 in cpp

59人阅读 评论(0) 收藏 举报
分类:

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:


Solution:

As long as we know how to find combination of certain length( in #77), this question would be very easy. Simply loop for every possible length, and in each loop we find all combinations of this length. 

Code: 

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> res; 
        sort(nums.begin(), nums.end());//sort to avoid duplicates
        res.push_back(vector<int>());//empty set 
     
        //find the combinations of length need starting from num[i]
        for(int need = 1;need <= nums.size(); need ++){//for each length 
            for(int i = 0; i < nums.size(); i ++)//start from each position to find combination
                find_subsets(i, need - 1, vector<int>(),nums, res);
        }
        return res;
    }
    
    void find_subsets(int start_ind, int need, vector<int> member,vector<int> &nums, vector<vector<int>> &res){
        //need does not include num[start_ind]
        if(need > nums.size() - 1 - start_ind) return;//if need > num between [start .....num.size() - 1], we could not do it. //Say need = 4 and the num[start position + 1....end] = [2,3] this could only provide 2 numbers < 4. We could terminate it 
        member.push_back(nums[start_ind]);
        if(need == 0){
            res.push_back(member);
             return;
        }
        for(int i = start_ind + 1; i < nums.size(); i ++)
            find_subsets(i, need - 1, member, nums, res);
        
    }
    
};



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7929次
    • 积分:1395
    • 等级:
    • 排名:千里之外
    • 原创:139篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档