【专题三:穷举vs暴搜vs深搜vs回溯vs剪枝】46. 全排列

1.题目解析

2.讲解算法原理

1.首先画出决策树,越详细越好

2.设计代码

  • 全局变量
    • List<List<Integer>> ret
    • List<Integer> path
    • boolean\[\] check
  • dfs函数
    • 仅关心某一节点在干什么
  • 细节问题
  • 回溯
    • 干掉path最后一个元素
    • 修改check权限
  • 剪枝
    • check中为true的不能使用,要剪掉
  • 递归出口
    • 遇到叶子结点的时候,直接添加结果

3.编写代码

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<>();
        check=new boolean[nums.length];
        dfs(nums);
        return ret;
    }
    public void dfs(int[] nums){
        if(nums.length==path.size()){
            ret.add (new ArrayList<>(path));
            return;
        }
        for(int i=0;i<nums.length;i++){
            if(check[i]==false){
                path.add(nums[i]);
                check[i]=true;
                dfs(nums);
                //回溯,恢复现场
                check[i]=false;
                path.remove(path.size()-1);
            }
            
            
        }
    }
}
相关推荐
电科_银尘9 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴12 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David13 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
塑料铲子15 小时前
你的 Skill 越多越蠢?Token 上下文爆炸的求生指南
机器学习·agent
Pniubi16 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK16 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
TsingtaoAI17 小时前
VeyForge:构建具身智能的AI 3D资产与Sim-to-Real数据引擎
人工智能·机器学习
上海潭龙东海科技有限公司17 小时前
智慧堆场动态模型三维实时孪生重构智能管控
大数据·网络·数据库·算法·重构
阿庆_AI研发工程师19 小时前
Stanford CS336 Lecture 10:大语言模型推理与性能优化
算法
用户73416810354820 小时前
基于MindSpore的深度残差收缩网络程序
算法