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

相关推荐
天河归来6 小时前
第三方接口不稳定,如何让核心任务继续完成
java·大数据
Knight_AL7 小时前
Java 文件下载时文件名中的 `#` 被转换成 `%23`?一次 URL 编码与解码问题排查
java·开发语言
砚底藏山河8 小时前
python量化自定义周期 K 线合成
java·开发语言·数据库·python·金融
猿究院_夏燊9 小时前
MySQL 的四种隔离级别
java·数据库·mysql
码流子9 小时前
移动收费怎么做?手持终端+App+收费中心的架构实践
java·开发语言·架构
霸道流氓气质9 小时前
AI 流式对话与实时聊天平台:SSE 解码竞态、有状态会话隔离与背压取消的 Vue3 + Spring AI 生产级实战
java·人工智能·spring
云创智城-yuncitys9 小时前
YunParking 4.0:JDK 17 与 Spring Boot 3.2 的停车云升级
java·开发语言·spring boot
文丑颜不良啊10 小时前
LeetCode1661~1680题目解析
java·leetcode
子非鱼@Itfuture10 小时前
关于前后端联调中登录状态/登录信息失效?
java·前端
郭小李10 小时前
openFeign入门
java·开发语言·前端