# leetcode #78 in cpp

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);

}

};

#### leetcode 78. Subsets-数组子集|回溯算法

2016-06-07 17:04:45

#### Leetcode 78 Subsets(打印全部子集）

2016-11-01 16:06:42

#### LeetCode78:Subsets

2015-07-06 17:33:29

#### LeetCode(78)Subset

2014-02-08 02:10:01

#### LeetCode78/90 subset I/II**

2015-04-06 15:22:22

#### [LeetCode 78] Subsets

2015-03-28 00:34:12

#### 两种回溯方法解决子集问题的思路 leetcode 78. Subsets

2017-02-16 10:34:34

#### LeetCode 78. Subsets 解题报告

2016-02-17 09:09:55

#### LeetCode cpp最新中文题解.pdf

2018年01月10日 866KB 下载