🌕 78. 子集

吞佛童子2022年6月9日
  • algorithm
  • backtrace
小于 1 分钟

🌕 78. 子集

难度: 🌕

问题描述

img_17.png


解法 1 - 二叉树思路

class Solution {
    List<List<Integer>> res = new LinkedList<>();
    public List<List<Integer>> subsets(int[] nums) {
        // 思路:
        // 无重复数组 & 无重复选取组合
        int len = nums.length;
        LinkedList<Integer> path = new LinkedList<>();
        mySol(nums, len, 0, path);
        return res;
    }

    private void mySol(int[] nums, int len, int index, LinkedList<Integer> path) {
        // 递归终止条件
        if(index == len) {
            res.add(new LinkedList<>(path));
            return;
        }
        // 类似二叉树,当前 index 有2种选择
        mySol(nums, len, index + 1, path);
        path.addLast(nums[index]);
        mySol(nums, len, index + 1, path);
        path.removeLast();
    }
}

输出 1

img_16.png


解法 2 - 通用

class Solution {
    List<List<Integer>> res = new LinkedList<>();
    public List<List<Integer>> subsets(int[] nums) {
        // 思路:
        // 无重复数组 & 无重复选取组合
        int len = nums.length;
        LinkedList<Integer> path = new LinkedList<>();
        mySol(nums, len, 0, path);
        return res;
    }

    private void mySol(int[] nums, int len, int index, LinkedList<Integer> path) {
        // 递归终止条件
        if(index > len) {
            return;
        }
        res.add(new LinkedList<>(path));
        for(int i = index; i < len; i ++) {
            path.addLast(nums[i]);
            mySol(nums, len, i + 1, path);
            path.removeLast();
        }
    }
}

输出

img_18.png

上次编辑于: 2022/6/20 下午8:24:47
贡献者: liuxianzhishou