力扣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);
        }
    }
}
相关推荐
怒放吧德德8 小时前
Spring Boot 实战:RSA+AES 接口全链路加解密(防篡改 / 防重放)
java·spring boot·后端
郑州光合科技余经理12 小时前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
大大水瓶12 小时前
Tomcat
java·tomcat
dustcell.12 小时前
haproxy七层代理
java·开发语言·前端
游离态指针12 小时前
以为发消息=下单成功?RabbitMQ从0到秒杀实战的完整踩坑笔记
java
ZPC821013 小时前
docker 镜像备份
人工智能·算法·fpga开发·机器人
ZPC821013 小时前
docker 使用GUI ROS2
人工智能·算法·fpga开发·机器人
琢磨先生David13 小时前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
颜酱13 小时前
栈的经典应用:从基础到进阶,解决LeetCode高频栈类问题
javascript·后端·算法
多恩Stone13 小时前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc