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],
[]
]
题意:给你一个集合,求所有的子集
思路:深搜
代码:
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
dfs(res, temp, nums, 0);
return res;
}
private void dfs(List<List<Integer>> res, List<Integer> temp, int[] nums, int j) {
res.add(new ArrayList<Integer>(temp));
for(int i = j; i < nums.length; i++) {
temp.add(nums[i]); //① 加入 nums[i]
dfs(res, temp, nums, i + 1); //② 递归
temp.remove(temp.size() - 1); //③ 移除 nums[i]
}
}
}
网友评论