【LeetCode 热题 HOT 100 中等】78. 子集(回溯)

简介: 【LeetCode 热题 HOT 100 中等】78. 子集(回溯)

题目


题目来源leetcode


leetcode地址:78. 子集,难度:中等。


题目描述(摘自leetcode):


给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
提示:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
nums 中的所有元素 互不相同


本地调试代码:


public static void main(String[] args) {
    int[] nums= new int[]{1,2,3};
    System.out.println(new Solution().subsets(nums));
}



题解


NO1:回溯找节点


思路:


思路:在递归方法调用过程中使用一个begin来进行直接控制组合,整个结果集添加操作在方法一开始进行,添加新的子集在循环中进行!


代码:


class Solution {
    private List<List<Integer>> res;
    //nums = [1,2,3]  =》 [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
    public List<List<Integer>> subsets(int[] nums) {
        res = new ArrayList<>();
        if (nums.length == 0){
            return res;
        }
        recursion(nums,0, new ArrayList<>());
        return res;
    }
    /**
     * 回溯过程中记录节点
     * @param nums
     * @param begin
     * @param pre
     */
    public void recursion(int nums[],int begin,List<Integer> pre){
        res.add(new ArrayList<>(pre)); /集合的深拷贝
        for (int i = begin; i < nums.length; i++) {  //begin用于间接直接控制组合
            pre.add(nums[i]);
            recursion(nums,i + 1, pre);
            pre.remove(pre.size() - 1);
        }
    }
}


相关文章
|
1月前
LeetCode 热题100——单调栈
LeetCode 热题100——单调栈
24 0
|
18天前
|
机器学习/深度学习 存储 算法
Python5种算法回溯+剪枝、字典序、递归交换、计数回溯、迭代法 实现全排列ll【力扣题47】
Python5种算法回溯+剪枝、字典序、递归交换、计数回溯、迭代法 实现全排列ll【力扣题47】
|
18天前
|
算法 数据挖掘 开发者
LeetCode题目55:跳跃游戏【python5种算法贪心/回溯/动态规划/优化贪心/索引哈希映射 详解】
LeetCode题目55:跳跃游戏【python5种算法贪心/回溯/动态规划/优化贪心/索引哈希映射 详解】
|
14天前
|
算法
【经典LeetCode算法题目专栏分类】【第3期】回溯问题系列:单词搜索、N皇后问题、判断有效数独、解数独
【经典LeetCode算法题目专栏分类】【第3期】回溯问题系列:单词搜索、N皇后问题、判断有效数独、解数独
|
17天前
|
机器学习/深度学习 存储 算法
LeetCode题目 90:五种算法 回溯\迭代\位掩码\字典树\动态规划实现 子集ll
LeetCode题目 90:五种算法 回溯\迭代\位掩码\字典树\动态规划实现 子集ll
|
17天前
|
存储 机器学习/深度学习 算法
力扣78题:生成子集
力扣78题:生成子集
|
1月前
|
算法
leetcode代码记录(子集
leetcode代码记录(子集
16 0
|
1月前
|
存储 算法
《LeetCode 热题 HOT 100》——寻找两个正序数组的中位数
《LeetCode 热题 HOT 100》——寻找两个正序数组的中位数
|
1月前
|
网络协议
《 LeetCode 热题 HOT 100》——无重复字符的最长子串
《 LeetCode 热题 HOT 100》——无重复字符的最长子串
|
1月前
《LeetCode 热题 HOT 100》—— 两数相加
《LeetCode 热题 HOT 100》—— 两数相加