力扣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);
        }
    }
}
相关推荐
wfeqhfxz25887826 小时前
YOLO13-C3k2-GhostDynamicConv烟雾检测算法实现与优化
人工智能·算法·计算机视觉
毕设源码-朱学姐6 小时前
【开题答辩全过程】以 基于JavaWeb的网上家具商城设计与实现为例,包含答辩的问题和答案
java
Aaron15886 小时前
基于RFSOC的数字射频存储技术应用分析
c语言·人工智能·驱动开发·算法·fpga开发·硬件工程·信号处理
C雨后彩虹8 小时前
CAS与其他并发方案的对比及面试常见问题
java·面试·cas·同步·异步·
_不会dp不改名_8 小时前
leetcode_3010 将数组分成最小总代价的子数组 I
算法·leetcode·职场和发展
java1234_小锋9 小时前
Java高频面试题:SpringBoot为什么要禁止循环依赖?
java·开发语言·面试
2501_944525549 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 账户详情页面
android·java·开发语言·前端·javascript·flutter
计算机学姐9 小时前
基于SpringBoot的电影点评交流平台【协同过滤推荐算法+数据可视化统计】
java·vue.js·spring boot·spring·信息可视化·echarts·推荐算法
Filotimo_9 小时前
Tomcat的概念
java·tomcat