递归、搜索与回溯-穷举vs暴搜vs深搜vs回溯vs剪枝:12.全排列

题目链接:46. 全排列(中等)

算法原理:

解法:递归

Java代码:

java 复制代码
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 王洋
 * Date: 2025-09-24
 * Time: 21:09
 */
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(path.size()==nums.length){
            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);
            }
        }
    }
}
相关推荐
YDS8296 小时前
DeepSeek RAG&MCP + Agent智能体项目 —— RAG知识库的搭建和接口实现
java·ai·springboot·agent·rag·deepseek
仰泳之鹅6 小时前
【C语言】自定义数据类型2——联合体与枚举
c语言·开发语言·算法
未若君雅裁7 小时前
MyBatis 一级缓存、二级缓存与清理机制
java·缓存·mybatis
AI人工智能+电脑小能手8 小时前
【大白话说Java面试题 第65题】【JVM篇】第25题:谈谈对 OOM 的认识
java·开发语言·jvm
人工智能培训8 小时前
大模型与传统小模型、传统NLP模型的核心差异解析
人工智能·深度学习·神经网络·机器学习·生成对抗网络
阿维的博客日记8 小时前
Nacos 为什么能让配置动态生效?(涉及 @RefreshScope 注解)
java·spring
雨辰AI8 小时前
SpringBoot3 + 人大金仓读写分离 + 分库分表 + 集群高可用 全栈实战
java·数据库·mysql·政务
x_yeyue9 小时前
三角形数
笔记·算法·数论·组合数学
辰海Coding10 小时前
MiniSpring框架学习-完成的 IoC 容器
java·spring boot·学习·架构