问题描述
- Given a set of distinct integers, nums, return all possible subsets (the power set).
- Note: The solution set must not contain duplicate subsets.
- Example :
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
问题分析
- 给定一个不含重复元素的数组,找出它的全部子集(子序列)
- 有以下两种思路:
- 每一个位置上的元素存在要或者不要的关系,要或者不要便是当前的两种决策:
- 在类似于寻找组合的过程中,不断向结果集中添加中间路径。
- 每一个位置上的元素存在要或者不要的关系,要或者不要便是当前的两种决策:
代码实现
- 方法1:
public List<List<Integer>> subsets(int[] nums) {
if (nums == null || nums.length == 0) {
return new ArrayList<>();
}
List<List<Integer>> res = new ArrayList<>();
findSubsets(nums, 0, new ArrayList<>(), res);
return res;
}
public void findSubsets(int[] nums, int i, ArrayList<Integer> path, List<List<Integer>> res) {
if (i == nums.length) {
res.add(new ArrayList<>(path));
return;
}
//不要i位置元素
findSubsets(nums, i + 1, path, res);
//要i位置元素
path.add(nums[i]);
findSubsets(nums, i + 1, path, res);
//回溯
path.remove(path.size() - 1);
return;
}
- 方法2:
public List<List<Integer>> subsets(int[] nums) {
if (nums == null || nums.length == 0) {
return new ArrayList<>();
}
List<List<Integer>> res = new ArrayList<>();
findSubsets(nums, 0, new ArrayList<>(), res);
return res;
}
public void findSubsets(int[] nums, int i, ArrayList<Integer> path, List<List<Integer>> res) {
if (i == nums.length) {
res.add(new ArrayList<>(path));
return;
}
res.add(new ArrayList<>(path));
for (int j = i; j < nums.length; ++j) {
path.add(nums[j]);
findSubsets(nums, j + 1, path, res);
path.remove(path.size() - 1);
}
return;
}