力扣 中等 46.全排列

文章目录

题目介绍

题解

代码如下:

java 复制代码
class Solution {
    List<List<Integer>> res = new ArrayList<>();// 存放符合条件结果的集合
    List<Integer> path = new ArrayList<>();// 用来存放符合条件结果
    boolean[] used; // 标记数组,记录数字是否被使用过
    public List<List<Integer>> permute(int[] nums) {
        used = new boolean[nums.length];   
        dfs(nums);
        return res;
    }
    public void dfs(int[] nums) {
        if (path.size() == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (used[i] == false) {
                path.add(nums[i]);
                used[i] = true;
                dfs(nums);
                // 回溯,撤销选择并从路径中移除当前数字      
                path.remove(path.size() - 1);
                used[i] = false;
            }
        }
    }
}
相关推荐
特立独行的猫A1 小时前
别再用 nohup 了:让应用在后台常驻的正确姿势与 systemd 服务详解
java·后端·python
一起_java2 小时前
技术文章-基于Dify-Agent的智能问答系统设计与实现
java·spring boot·后端·agent·dify
Flynn Liang3 小时前
I/O 密集型高并发实战:Java 服务 10 维优化,从线程打满到 10 万 QPS
java·spring boot·性能优化·高并发·系统设计·虚拟线程·io密集型
吃我一窝jio4 小时前
Python与Go线程模型深度对比
java·开发语言·python
这个昵称不容易4 小时前
SpringBoot 购物推荐网站的设计与实现:120 个 Java 文件、147 个接口、13 张表,附真实运行截图
java·springboot·毕设
文丑颜不良啊5 小时前
LeetCode3041~3060题目解析
java·leetcode
罗西的思考5 小时前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
文丑颜不良啊6 小时前
LeetCode3101~3120题目解析
java·leetcode
Resean02236 小时前
SpringMVC 6+源码分析(十一)视图渲染与异步请求(收尾篇)
java·spring·springmvc
靠沿7 小时前
MySQL数据库进阶——存储过程和触发器
java·数据库·mysql