刷刷刷 Day 28 | 78. 子集

78. 子集

LeetCode题目要求

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

示例

输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
解题思路

子集需要的是所有可能性,所以要取所有节点

上代码

class Solution {

    private List<List<Integer>> res = new ArrayList<>();
    private Deque<Integer> path = new LinkedList<>();

    public List<List<Integer>> subsets(int[] nums) {
        backtracking(nums, 0);
        return res;
    }

    private void backtracking(int[] nums, int startIndex) {
        res.add(new ArrayList<>(path));
        // 终止条件
        if (startIndex >= nums.length) {
            return;
        }

        // 单层循环
        for (int i = startIndex; i < nums.length; i++) {
            path.add(nums[i]);
            backtracking(nums, i + 1);
            path.removeLast();
        }
    }
}

附:学习资料链接

posted @ 2023-01-29 22:53  blacksonny  阅读(10)  评论(0编辑  收藏  举报