【回溯】Leetcode 46. 全排列【中等】

全排列

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

示例:

输入 :nums = 1,2,3
输出\[1,2,3,1,3,2,2,1,3,2,3,1,3,1,2,3,2,1]

解题思路

  • 1、使用回溯算法来生成所有可能的全排列。
  • 2、从第一个位置开始,依次将每个数字放入当前位置,并递归生成下一个位置的排列。
  • 3、当所有位置都填满时,将当前排列加入结果集。

具体步骤

  • 1、初始化一个空列表 result,用于存储所有可能的全排列。
  • 2、编写一个递归函数 backtrack,该函数接受当前正在处理的子数组 nums、 以及当前正在构建的排列 tempList。
  • 3、在 backtrack 中,如果 current 的长度等于 nums 的长度,
  • 说明已经构建出了一个完整的排列,将其加入到 result 中。
  • 4、否则,遍历数组 nums,对于每个未被使用过的数字,将其添加到 tempList 中,并递归调用 backtrack 处理剩余的子数组。
  • 5、在递归调用完成后,要将刚刚添加到 tempList 中的数字从中删除,以便后续使用。

Java实现

java 复制代码
public class Permutation {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(nums, new ArrayList<>(), result);
        return result;
    }

    private void backtrack(int[] nums, List<Integer> tempList, List<List<Integer>> result) {
        if (tempList.size() == nums.length) {
            result.add(new ArrayList<>(tempList));
        } else {
            for (int i = 0; i < nums.length; i++) {
                if (tempList.contains(nums[i])) continue; // element already exists, skip
                tempList.add(nums[i]);
                backtrack(nums, tempList, result);
                //回溯一层后,对应移除上一层的末尾元素
                tempList.remove(tempList.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        Permutation permutation = new Permutation();

        // Test Case 1
        int[] nums1 = {1, 2, 3};
        List<List<Integer>> result1 = permutation.permute(nums1);
        System.out.println("Test Case 1:");
        printResult(result1);

        // Test Case 2
        int[] nums2 = {0, 1};
        List<List<Integer>> result2 = permutation.permute(nums2);
        System.out.println("Test Case 2:");
        printResult(result2);
    }

    private static void printResult(List<List<Integer>> result) {
        for (List<Integer> list : result) {
            System.out.println(list);
        }
        System.out.println();
    }
}

时间空间复杂度

  • 时间复杂度:O(N!),其中N是数组nums的长度。因为生成全排列的数量是N的阶乘。

  • 空间复杂度:O(N!),存储所有可能的全排列。

相关推荐
BothSavage24 分钟前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn26 分钟前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽2 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
先吃饱再说18 小时前
判断回文字符串,从一行代码到双指针优化
算法
黄敬峰20 小时前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法
得物技术1 天前
从狂野代码到按目标生产:得物推荐 AI Harness 的工程化实践|AICon 演讲整理
人工智能·算法·架构
AI小老六1 天前
SkillOpt 架构拆解:把 Skill 文本当参数,用执行轨迹训练 Agent
后端·算法·ai编程
胡萝卜术1 天前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
Asize1 天前
初识DFS 与 BFS:递归、队列与图遍历
算法