【陪伴式刷题】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答案,欢迎路过的大佬指点。

相关推荐
Cosmoshhhyyy10 小时前
《Effective Java》解读第5条:优先考虑依赖注入来引用资源
java
.柒宇.11 小时前
力扣hot100----15.三数之和(java版)
java·数据结构·算法·leetcode
程序员卷卷狗12 小时前
JVM 调优实战:从线上问题复盘到精细化内存治理
java·开发语言·jvm
cj63411815012 小时前
【MySQL】mysqldump使用方法
java·后端
JIngJaneIL12 小时前
停车场管理|停车预约管理|基于Springboot的停车场管理系统设计与实现(源码+数据库+文档)
java·数据库·spring boot·后端·论文·毕设·停车场管理系统
杰克尼13 小时前
二分查找为什么总是写错
java·数据结构·算法
半旧夜夏15 小时前
【分布式缓存】Redis持久化和集群部署攻略
java·运维·redis·分布式·缓存
短视频矩阵源码定制15 小时前
矩阵系统源码推荐:技术架构与功能完备性深度解析
java·人工智能·矩阵·架构
Eiceblue15 小时前
使用 Java 将 Excel 工作表转换为 CSV 格式
java·intellij-idea·excel·myeclipse
漂流幻境15 小时前
IntelliJ IDEA的Terminal中执行ping命令时遇到的“No route to host“问题
java·ide·intellij-idea