【专题三:穷举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);
            }
            
            
        }
    }
}
相关推荐
Pniubi13 分钟前
01背包类问题-力扣416.分割等和子集
算法·leetcode·职场和发展
罗西的思考11 小时前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
kyle~16 小时前
模型预测控制(MPC)
算法·机器人·控制·传感器
Be for thing16 小时前
Pytorch【12】transforms进阶|图像数据增强实战,提升模型泛化能力
人工智能·pytorch·机器学习
武子康17 小时前
AI通关了,游戏就算通过测试了吗?
人工智能·游戏·机器学习
牢姐与蒯17 小时前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好18 小时前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频
电科_银尘18 小时前
【大模型算法与工程 02】线性回归与逻辑回归:从损失函数到决策边界
算法·逻辑回归·线性回归
玄昌盛不会编程19 小时前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode
linweidong21 小时前
RTX 4090 Ubuntu + ComfyUI + comfy-kitchen 0.2.41 完整部署文档
机器学习·云原生·conda·pandas·scikit-learn