力扣回溯 深度优先搜索dfs之78. 子集
给你一个整数数组 nums
,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3] 输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0] 输出:[[],[0]]
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<>(), nums, 0);
return result;
}
private void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] nums, int start) {
result.add(new ArrayList<>(tempList));
for (int i = start; i < nums.length; i++) {
tempList.add(nums[i]);
backtrack(result, tempList, nums, i + 1);
// 从tempList中移除最后一个元素。
tempList.remove(tempList.size() - 1);
}
}
}
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<>(), nums, 0);
return result;
}
public void backtrack(List<List<Integer>> result, List<Integer> subList,
int[] nums, int start) {
result.add(new ArrayList<>(subList));
for (int i = start; i < nums.length; i++) {
subList.add(nums[i]);
backtrack(result, subList, nums, i + 1);
subList.remove(subList.size() - 1);
}
}
}