leetcode78. 子集
给你一个整数数组 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 void dfs(List<List<Integer>> res, List<Integer>cnt, int st, int len, int[] nums) {if(len == cnt.size()) res.add(new ArrayList<Integer>(cnt));//System.out.println(len+" "+ cnt.size());for(int i = st; i < nums.length; i++) {cnt.add(nums[i]);dfs(res, cnt, i+1, len+1, nums);cnt.remove(cnt.size() - 1);}}public List<List<Integer>> subsets(int[] nums) {List<List<Integer>>res = new ArrayList<>();List<Integer>cnt = new ArrayList<>();//for(int i = 0; i < nums.length; i++) cnt.add(nums[i]);dfs(res, cnt, 0, 0,nums);return res;}
首先要滤清回溯的思路,
每次做判断选或者不选,然后恢复状态