1. 题目
给你一个整数数组 nums ,返回该数组所有可能的子集(幂集)。解集不能包含重复的子集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
提示:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
Related Topics 位运算 数组 回溯算法
👍 956 👎 0
2. 题解
2.1 解法1: 递归1
主要思路, 遍历数组每一个元素, 每次可以选这个元素或者不选这个元素, 每次操作后进行回溯, 不影响下一次dfs
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
dfs(0, new ArrayList<>(), nums, ans);
return ans;
}
public void dfs(int index, List<Integer> list, int[] nums, List<List<Integer>> ans) {
if (index == nums.length) {
ans.add(new ArrayList<>(list));
return;
}
list.add(nums[index]);
dfs(index + 1, list, nums, ans);
list.remove(list.size() - 1);
dfs(index + 1, list, nums, ans);
}
}
2.2 解法1: 递归dfs–节点遍历
class Solution {
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
dfs(-1, nums, new ArrayList<>());
return ans;
}
/**
* 递归dfs
* 1. 递归边界: 当当前节点list长度大于数组长度时, 停止递归
* 2. 下一层递归: 添加index后的元素到list并进入下一层递归
*
* @param index 当前访问索引
* @param nums 源数组
* @param list 当前节点含有的元素
*/
public void dfs(int index, int[] nums, List<Integer> list) {
if (list.size() > nums.length) {
return;
}
ans.add(list);
for (int i = index + 1; i < nums.length; i++) {
List<Integer> tempList = new ArrayList<>(list);
tempList.add(nums[i]);
dfs(i, nums, tempList);
}
}
}
参考题解:
官方题解