Subsets(Medium)子集
Given a set of distinct integers, nums, return all possible subsets.
Notes:
- 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],
[]
]
解题思路:回溯+DFS
子集类问题类似Combination,以输入数组[1, 2, 3]分析,根据题意, 最终返回结果中子集类的元素应该按照升序排列,故首先需要对原数组进行排序。题目的第二点要求是子集不能重复,至此原题即转化为数学中的组合问题。我们首先尝试使用 DFS 进行求解,大致步骤如下:
- [1] -> [1, 2] -> [1, 2, 3]
- [2] -> [2, 3]
- [3]
将上述过程转化为代码即为对数组遍历,每一轮都保存之前的结果并将其依次加入到最终返回结果中。
public class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
if (nums == null || nums.length == 0) {
return result;
}
Arrays.sort(nums);
dfs(nums, 0, list, result);
return result;
}
private void dfs(int[] nums, int pos, List<Integer> list,
List<List<Integer>> ret) {
//add temp result first
ret.add(new ArrayList<Integer>(list));
for (int i = pos; i < nums.length; i++) {
list.add(nums[i]);
dfs(nums, i + 1, list, ret);
list.remove(list.size() - 1);
}
}
}