78. 子集
题目描述
给你一个整数数组 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] <= 10nums中的所有元素 互不相同
解法
回溯法的基本模板:
res = [] path = [] def backtrack(未探索区域, res, path): if path 满足条件: res.add(path) # 深度拷贝 # return # 如果不用继续搜索需要 return for 选择 in 未探索区域当前可能的选择: if 当前选择符合要求: path.add(当前选择) backtrack(新的未探索区域, res, path) path.pop()
Python3
class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: def dfs(nums, i, res, path): res.append(copy.deepcopy(path)) while i < len(nums): path.append(nums[i]) dfs(nums, i + 1, res, path) path.pop() i += 1 res, path = [], [] dfs(nums, 0, res, path) return res
Java
class Solution { public List<List<Integer>> subsets(int[] nums) { List<Integer> path = new ArrayList<>(); List<List<Integer>> res = new ArrayList<>(); dfs(nums, 0, res, path); return res; } private void dfs(int[] nums, int i, List<List<Integer>> res, List<Integer> path) { res.add(new ArrayList<>(path)); while (i < nums.length) { path.add(nums[i]); dfs(nums, i + 1, res, path); path.remove(path.size() - 1); ++i; } } }