子集000

题目链接

子集

题目描述

注意点

  • nums 中的所有元素 互不相同
  • 解集 不能 包含重复的子集
  • 可以按 任意顺序 返回解集

解答思路

  • 使用深度优先遍历找到所有的子集

代码

class Solution {
    
    
    public List<List<Integer>> subsets(int[] nums) {
    
    
        List<List<Integer>> res = new ArrayList<>();
        int depth = 0, idx = 0;
        List<Integer> sonRes = new ArrayList<>();
        res.add(sonRes);
        dfs(nums, res, sonRes, depth, idx);
        return res;
    }

    public void dfs(int[] nums, List<List<Integer>> res, List<Integer> sonRes, int depth, int idx) {
    
    
        if (depth > nums.length) {
    
    
            return;
        }
        for (int i = idx; i < nums.length; i++) {
    
    
            sonRes.add(nums[i]);
            res.add(new ArrayList<>(sonRes));
            dfs(nums, res, sonRes, depth + 1, i + 1);
            sonRes.remove(sonRes.size() - 1);
        }
    }
}

关键点

猜你喜欢

转载自blog.csdn.net/weixin_51628158/article/details/130843367
000