给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subsets
思路:
根据不同的子集的范围来遍历
class Solution {public List<List<Integer>> subsets(int[] nums) {List<List<Integer>> res = new LinkedList<>();if (nums.length == 0){return res;}Deque<Integer> path = new ArrayDeque<Integer>();int len = nums.length;for (int size = 0; size <= nums.length; size++) {dfs(0,nums, path, res, size); // 不同的子集大小}return res;}private void dfs(int first,int[] nums, Deque<Integer> path, List<List<Integer>> res,int size) {if (path.size() == size) {res.add(new ArrayList<>(path));return;}for (int i = first; i < nums.length; i++) {path.add(nums[i]);dfs(i + 1,nums,path,res,size);path.remove(nums[i]);}}}
