子集

子集

题目:
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。

示例:

输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

解题思路:用回溯算法解决,在纸上画出整个子集[[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]]可以总结出规律

class Solution {
    
    private List<List<Integer>> ans = new ArrayList();
    // private Set<List<Integer>> set = new HashSet();
    
    public List<List<Integer>> subsets(int[] nums) {
        dfs(nums, new ArrayList<Integer>(), 0);
        return ans;
    }
    
    private void dfs(int[] nums, List<Integer> list, int cur) {
        ans.add(new ArrayList<>(list));
        for (int j = cur; j < nums.length; j++) {
            list.add(nums[j]);
            dfs(nums, list, j + 1);
            list.remove(list.size() - 1);
        }
    }
}
原文地址:https://www.cnblogs.com/katoMegumi/p/13924485.html