力扣HOT100 - 46. 全排列

解题思路:

回溯

假设给定数组nums为[1, 2, 3],首先将其转换为List<Integer>类型的output为[1, 2, 3]。

在backtrack方法中,初始时first为0,所以进入第一个for循环,交换output中第一个元素和自身,然后递归调用backtrack方法,此时first为1,再次进入for循环,交换output中第二个元素(即2)和自身。这样得到的output为[1, 2, 3],添加到结果集中。

接着回到第一个for循环,再次交换output中第一个元素和自身,此时成为[2, 1, 3],再次递归调用backtrack方法,得到的output为[2, 1, 3],添加到结果集中。

依次类推,通过不断交换元素的位置和递归调用backtrack方法,可以生成所有可能的排列组合。最终得到的结果为[[1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1]],即给定数组[1, 2, 3]的全排列结果。

java 复制代码
class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> output = new ArrayList<>();
        for (int num : nums) {
            output.add(num);
        }

        int n = nums.length;
        backtrack(n, output, res, 0);
        return res;
    }

    public void backtrack(int n, List<Integer> output, List<List<Integer>> res, int first) {
        if (first == n)
            res.add(new ArrayList<Integer>(output));
        for (int i = first; i < n; i++) {
            Collections.swap(output, first, i);
            backtrack(n, output, res, first + 1);
            Collections.swap(output, first, i);
        }
    }
}
相关推荐
sin_hielo10 分钟前
leetcode 3578
数据结构·算法·leetcode
invicinble11 分钟前
spring相关系统性理解,企业级应用
java·spring·mybatis
jiayong2333 分钟前
Spring IOC 与 AOP 核心原理深度解析
java·spring·log4j
ShiMetaPi39 分钟前
SAM(通用图像分割基础模型)丨基于BM1684X模型部署指南
人工智能·算法·ai·开源·bm1684x·算力盒子
前端小白在前进41 分钟前
力扣刷题:无重复字符的最长子串
算法·leetcode·职场和发展
卿雪41 分钟前
Redis 线程模型:Redis为什么这么快?Redis为什么引入多线程?
java·数据库·redis·sql·mysql·缓存·golang
小小的橙菜吖!43 分钟前
联合体的学习
学习·算法
lkbhua莱克瓦241 小时前
IO流练习(修改文件中的数据)
java·windows·学习方法·io流·java练习题·io流练习
老华带你飞1 小时前
汽车销售|汽车报价|基于Java汽车销售系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端·汽车
西岭千秋雪_1 小时前
MySQL集群搭建
java·数据库·分布式·mysql