78. Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
给定一个不同的整数数组 nums[],返回所有可能的子集(幂集)。
根据77题类似的方法,也是用递归来做
public class Subsets { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> res = new ArrayList<>(); res.add(new ArrayList<>()); dfs(res, new ArrayList<>(), nums, 0); return res; } public static void dfs(List<List<Integer>> res, List<Integer> temp, int[] nums, int start) { if (start == nums.length) { return; } for (int i = start; i < nums.length; i++) { temp.add(nums[i]); res.add(new ArrayList<>(temp)); dfs(res, temp, nums, i + 1); temp.remove(temp.size() - 1); } } public static void main(String[] args) { Subsets subsets = new Subsets(); int[] nums = {1, 2, 3}; subsets.subsets(nums); } }