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

相关推荐
sunshine22 girl3 小时前
Java学习七 Java 项目实战1-项目创建和主页面搭建
java·开发语言·学习
code2cat3 小时前
Java进阶篇之AtomicStampedReference:引用回到原值,版本戳仍能记住变化
java·cas·并发编程·aba
泡茶喝茶写代码5 小时前
A股量化数据工程:从 REST 接口到策略信号(第 8 篇):成长能力因子:营收与利润增速
java·python·股票数据api·股票数据api接口·股票量化数据api·股票量化数据接口·股票数据api数据
\光辉岁月/5 小时前
7.javase-面向对象
java·开发语言
weixin_531094696 小时前
heap_4内存管理
java·开发语言·算法
程序员南飞6 小时前
win系统安装minio
java·数据结构·算法
Escalating_xu6 小时前
【Python】使用库:标准库、第三方库、pip、项目实战与程序打包
java·python·pip
longlongzihan7 小时前
LeetCode 5. 最长回文子串:从暴力匹配到中心扩展的思维演进
c++·算法·leetcode
Wang's Blog7 小时前
Java框架 SpringCloud 快速入门: 过滤器链执行顺序
java·spring cloud
苦瓜打怪兽7 小时前
leetcode 热题100(11. 盛最多水的容器)
python·算法·leetcode