Subsets
最后更新于:2022-04-02 01:12:01
# Subsets - 子集
### Source
- leetcode: [Subsets | LeetCode OJ](https://leetcode.com/problems/subsets/)
- lintcode: [(17) Subsets](http://www.lintcode.com/en/problem/subsets/)
### Problem
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],
[]
]
~~~
### 题解
子集类问题类似Combination,以输入数组`[1, 2, 3]`分析,根据题意,最终返回结果中子集类的元素应该按照升序排列,故首先需要对原数组进行排序。题目的第二点要求是子集不能重复,至此原题即转化为数学中的组合问题。我们首先尝试使用 [DFS](# "Depth-First Search, 深度优先搜索") 进行求解,大致步骤如下:
1. `[1] -> [1, 2] -> [1, 2, 3]`
1. `[2] -> [2, 3]`
1. `[3]`
将上述过程转化为代码即为对数组遍历,每一轮都保存之前的结果并将其依次加入到最终返回结果中。
### Python
~~~
class Solution:
# @param {integer[]} nums
# @return {integer[][]}
def subsets(self, nums):
if nums is None:
return []
result = []
nums.sort()
self.dfs(nums, 0, [], result)
return result
def dfs(self, nums, pos, list_temp, ret):
# append new object with []
ret.append([] + list_temp)
for i in xrange(pos, len(nums)):
list_temp.append(nums[i])
self.dfs(nums, i + 1, list_temp, ret)
list_temp.pop()
~~~
### C++
~~~
class Solution {
public:
vector> subsets(vector& nums) {
vector > result;
if (nums.empty()) return result;
sort(nums.begin(), nums.end());
vector list;
dfs(nums, 0, list, result);
return result;
}
private:
void dfs(vector& nums, int pos, vector &list,
vector > &ret) {
ret.push_back(list);
for (int i = pos; i < nums.size(); ++i) {
list.push_back(nums[i]);
dfs(nums, i + 1, list, ret);
list.pop_back();
}
}
};
~~~
### Java
~~~
public class Solution {
public List
';
- > subsets(int[] nums) {
List
- > result = new ArrayList
- >();
List
- > ret) {
// add temp result first
ret.add(new ArrayList