穷举vs暴搜vs深搜vs回溯vs剪枝 算法专题

一. 全排列

全排列

java 复制代码
class Solution {
    List<List<Integer>> ret;
    List<Integer> path;
    boolean[] check;
    public List<List<Integer>> permute(int[] nums) {
        ret = new ArrayList<>();//存放结果
        path = new ArrayList<>();存放每个路径的path
        check = new boolean[nums.length];//记录是否被使用, 对应是下标

        dfs(nums);
        return ret;
    }

    public void dfs(int[] nums){
        if(path.size() == nums.length){//全部遍历完
            ret.add(new ArrayList<>(path));//添加结果
            return;
        }
        for(int i = 0; i < nums.length; i++){
            if(!check[i]){
                path.add(nums[i]);
                check[i] = true;
                dfs(nums);
                //还原现场
                check[i] = false;
                path.remove(path.size() - 1);
            }
        }
    }
}

二. 子集

子集

先画决策树, 再设计代码

解法一:

java 复制代码
class Solution {
    List<List<Integer>> ret;
    List<Integer> path;
    public List<List<Integer>> subsets(int[] nums) {
        ret = new ArrayList<>();
        path = new ArrayList<>();

        dfs(nums, 0);
        return ret;
    }

    public void dfs(int[] nums, int i){//要选择的下标
        if(i == nums.length){
            ret.add(new ArrayList<>(path));
            return ;
        }
        //选
        path.add(nums[i]);
        dfs(nums, i + 1);
        //恢复现场
        path.remove(path.size() - 1);
        //不选
        dfs(nums, i + 1);
    }
}

解法二: 按照数量添加

java 复制代码
class Solution {
    List<List<Integer>> ret;
    List<Integer> path;

    public List<List<Integer>> subsets(int[] nums) {
        ret = new ArrayList<>();
        path = new ArrayList<>();

        dfs(nums, 0);
        return ret;
    }

    public 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);//恢复现场
        }

    }
}
相关推荐
唐梓航-求职中4 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
仟濹4 小时前
【算法打卡day3 | 2026-02-08 周日 | 算法: BFS】3_卡码网99_计数孤岛_BFS | 4_卡码网100_最大岛屿的面积DFS
算法·深度优先·宽度优先
Ll13045252984 小时前
Leetcode二叉树part4
算法·leetcode·职场和发展
颜酱4 小时前
二叉树遍历思维实战
javascript·后端·算法
宝贝儿好4 小时前
第二章: 图像处理基本操作
算法
小陈phd4 小时前
多模态大模型学习笔记(二)——机器学习十大经典算法:一张表看懂分类 / 回归 / 聚类 / 降维
学习·算法·机器学习
@––––––4 小时前
力扣hot100—系列4-贪心算法
算法·leetcode·贪心算法
CoovallyAIHub4 小时前
让本地知识引导AI追踪社区变迁,让AI真正理解社会现象
深度学习·算法·计算机视觉
CoderCodingNo4 小时前
【GESP】C++ 二级真题解析,[2025年12月]第一题环保能量球
开发语言·c++·算法
yumgpkpm4 小时前
预测:2026年大数据软件+AI大模型的发展趋势
大数据·人工智能·算法·zookeeper·kafka·开源·cloudera