# 78. Subsets 子集

@TOC

## # 题目描述

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: 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],
[]
]
``````

## # 解题方法

### # 递归

C++代码如下：

``````class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
dfs(res, {}, nums, 0);
return res;
}
void dfs(vector<vector<int>>& res, vector<int> path, vector<int>& nums, int index) {
if (index >= nums.size()) {
res.push_back(path);
return;
}
dfs(res, path, nums, index + 1);
path.push_back(nums[index]);
dfs(res, path, nums, index + 1);
}
};
``````

python代码如下：

``````class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
self.dfs(nums, 0, res, [])
return res

def dfs(self, nums, index, res, path):
res.append(path)
for i in xrange(index, len(nums)):
self.dfs(nums, i + 1, res, path + [nums[i]])
``````

### # 回溯法

C++解法，同样的也是回溯法。

C++代码如下：

``````class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
vector<int> path;
helper(nums, res, path, 0);
return res;
}
void helper(const vector<int>& nums, vector<vector<int>>& res, vector<int>& path, int start) {
res.push_back(path);
for (int i = start; i < nums.size(); i ++) {
path.push_back(nums[i]);
helper(nums, res, path, i + 1);
path.pop_back();
}
}
};
``````

## # 日期

2018 年 2 月 24 日 2018 年 12 月 20 日 —— 感冒害的我睡不着 2019 年 9 月 25 日 —— 做梦都在秋招，这个秋天有毒