【陪伴式刷题】Day 25|回溯|46.全排列(Permutations )

刷题顺序按照代码随想录建议

题目描述

英文版描述

Given an array nums of distinct integers, return all the possible permutations . You can return the answer in any order.

Example 1:

Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Example 2:

Input: nums = [0,1] Output: [[0,1],[1,0]]

Example 3:

Input: nums = [1] Output: [[1]]

Constraints:

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • All the integers of nums are unique.

英文版地址

leetcode.com/problems/pe...

中文版描述

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

示例 1:

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

示例 2:

输入: nums = [0,1] 输出: [[0,1],[1,0]]

示例 3:

输入: nums = [1] 输出: [[1]]

提示:

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • nums 中的所有整数 互不相同

中文版地址

leetcode.cn/problems/pe...

解题方法

递归法

java 复制代码
class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> level = new ArrayList<>();

    public List<List<Integer>> permute(int[] nums) {
        int[] flags = new int[nums.length];
        Arrays.fill(flags, 0);
        backTracking(nums, flags);
        return result;
    }

    private void backTracking(int[] nums, int[] flags) {
        if (level.size() == nums.length) {
            result.add(new ArrayList<>(level));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (flags[i] == 1) {
                continue;
            }
            level.add(nums[i]);
            flags[i] = 1;
            backTracking(nums, flags);
            flags[i] = 0;
            level.remove(level.size() - 1);
        }
    }
}

复杂度分析

一碰到回溯我就不算不清楚复杂度了......如下Leetcode答案,欢迎路过的大佬指点。

相关推荐
Elias不吃糖12 小时前
Java Lambda 表达式
java·开发语言·学习
夏鹏今天学习了吗12 小时前
【LeetCode热题100(83/100)】最长递增子序列
算法·leetcode·职场和发展
情缘晓梦.12 小时前
C语言指针进阶
java·开发语言·算法
AlenTech14 小时前
155. 最小栈 - 力扣(LeetCode)
算法·leetcode·职场和发展
南知意-14 小时前
IDEA 2025.3 版本安装指南(完整图文教程)
java·intellij-idea·开发工具·idea安装
码农水水14 小时前
蚂蚁Java面试被问:混沌工程在分布式系统中的应用
java·linux·开发语言·面试·职场和发展·php
海边的Kurisu15 小时前
苍穹外卖日记 | Day4 套餐模块
java·苍穹外卖
毕设源码-邱学长15 小时前
【开题答辩全过程】以 走失儿童寻找平台为例,包含答辩的问题和答案
java
坚持不懈的大白15 小时前
Leetcode学习笔记
笔记·学习·leetcode
他们叫我技术总监15 小时前
Python 列表、集合、字典核心区别
android·java·python