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

相关推荐
怒放吧德德3 小时前
Netty 4.2 入门指南:从概念到第一个程序
java·后端·netty
雨中飘荡的记忆5 小时前
大流量下库存扣减的数据库瓶颈:Redis分片缓存解决方案
java·redis·后端
心之语歌7 小时前
基于注解+拦截器的API动态路由实现方案
java·后端
华仔啊9 小时前
Stream 代码越写越难看?JDFrame 让 Java 逻辑回归优雅
java·后端
ray_liang9 小时前
用六边形架构与整洁架构对比是伪命题?
java·架构
Ray Liang10 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Java水解10 小时前
Java 中间件:Dubbo 服务降级(Mock 机制)
java·后端
SimonKing14 小时前
OpenCode AI辅助编程,不一样的编程思路,不写一行代码
java·后端·程序员
FastBean14 小时前
Jackson View Extension Spring Boot Starter
java·后端
Seven9716 小时前
剑指offer-79、最⻓不含重复字符的⼦字符串
java