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

}

};

• 本文已收录于以下专栏：

## LeetCode78:Subsets

Given a set of distinct integers, nums, return all possible subsets.Note: Elements in a subset must...
• u012501459
• 2015年07月06日 17:33
• 3290

## LeetCode78/90 subset I/II**

• Lu597203933
• 2015年04月06日 15:22
• 1517

## LeetCode OJ 系列之78 Subsets --Python

Problem: Given a set of distinct integers, nums, return all possible subsets. Note: Elements in...
• ln152315
• 2015年11月18日 22:07
• 917

## [LeetCode 78] Subsets

• ever223
• 2015年03月28日 00:34
• 679

## LeetCode(78)Subset

• feliciafay
• 2014年02月08日 02:10
• 2766

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

• happyaaaaaaaaaaa
• 2016年06月07日 17:04
• 4335

## [leetcode-78]subsets(java)

• zdavb
• 2015年08月05日 22:42
• 919

## LeetCode-55-Jump Game(贪心)-Medium

• eddy_liu
• 2016年02月04日 08:30
• 1534

## leetcode 78

• peter19930127
• 2017年06月28日 18:24
• 27

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

leetcode 78. Subsets  注意：理解回溯算法尽量采用动态规划的思路。 第一种，例子{1,2,3} ，子集问题即为各位有无两种情况，那么就可以直接搜索下去。 im...
• chengdezhi2011
• 2017年02月16日 10:34
• 566

举报原因： 您举报文章：leetcode #78 in cpp 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)