穷举vs暴搜vs深搜vs回溯vs剪枝专题一>子集

题目:


两个方法本质就是决策树的画法不同

方法一解析:


代码:

java 复制代码
class Solution {
    private List<List<Integer>> ret;//返回结果
    private List<Integer> path;//记录路径,注意返回现场
    public List<List<Integer>> subsets(int[] nums) {
        path = new ArrayList<>();
        ret = new ArrayList<>();
        dfs(nums,0);
        return ret;
    }


    //i表示选择到了那一层
    private void dfs(int[] nums, int indx){
        //递归出口
        if(indx == nums.length){
            ret.add(new ArrayList<>(path));
            return;
        }

        //选某个元素
        path.add(nums[indx]);
        dfs(nums,indx+1);
        path.remove(path.size()-1);//回复现场


        //不选某个元素
        dfs(nums,indx+1);
    }
}

方法二解析:


代码:

java 复制代码
 private List<List<Integer>> ret;//返回结果
    private List<Integer> path;//记录路径
    public List<List<Integer>> subsets(int[] nums) {
        path = new ArrayList<>();
        ret = new ArrayList<>();
        dfs(nums,0);
        return ret;
    }

    private void dfs(int[] nums, int pos){
        ret.add(new ArrayList<>(path));
        for(int i = pos; i < nums.length; i++){
            path.add(nums[i]);
            //每一层只能往选过的元素,再往选
            dfs(nums,i+1);
            path.remove(path.size()-1);//回复现场
        }
    }
相关推荐
Han.miracle2 小时前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode
mit6.8244 小时前
前后缀分解
算法
你好,我叫C小白4 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
寂静山林7 小时前
UVa 10228 A Star not a Tree?
算法
Neverfadeaway7 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
Madison-No78 小时前
【C++】探秘vector的底层实现
java·c++·算法
Swift社区8 小时前
LeetCode 401 - 二进制手表
算法·leetcode·ssh
派大星爱吃猫8 小时前
顺序表算法题(LeetCode)
算法·leetcode·职场和发展
liu****8 小时前
8.list的模拟实现
linux·数据结构·c++·算法·list
地平线开发者9 小时前
征程 6 | 征程 6 工具链如何支持 Matmul/Conv 双 int16 输入量化?
算法·自动驾驶