长生栈 长生栈
首页
  • 编程语言

    • C语言
    • C++
    • Java
    • Python
  • 数据结构和算法

    • 全排列算法实现
    • 动态规划算法
  • CMake
  • gitlab 安装和配置
  • docker快速搭建wordpress
  • electron+react开发和部署
  • Electron-创建你的应用程序
  • ImgUI编译环境
  • 搭建图集网站
  • 使用PlantUml画时序图
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

Living Team

编程技术分享
首页
  • 编程语言

    • C语言
    • C++
    • Java
    • Python
  • 数据结构和算法

    • 全排列算法实现
    • 动态规划算法
  • CMake
  • gitlab 安装和配置
  • docker快速搭建wordpress
  • electron+react开发和部署
  • Electron-创建你的应用程序
  • ImgUI编译环境
  • 搭建图集网站
  • 使用PlantUml画时序图
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 编程语言

  • 数据结构和算法

    • 全排列算法实现
    • 动态规划算法
    • Leetcode-46-全排列
      • 题目说明
      • 题解
    • Leetcode-78-子集
    • Leetcode-90-子集 II
  • 计算机组成原理

  • 操作系统

  • 计算机网络

  • 数据库

  • 设计模式

  • 基础
  • 数据结构和算法
DC Wang
2022-11-22
目录

Leetcode-46-全排列

# Leetcode-46-全排列

# 题目说明

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

示例 1:

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

示例 2:

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

示例 3:

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

提示:

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

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/permutations

# 题解

回溯法+剪枝

def backtracking(nums, result, used, permutation):
    if len(nums) == len(permutation):
        result.append(permutation.copy())
        return
    for i in range(0, len(nums)):
        if used[i] == False:
            permutation.append(nums[i])
            used[i] = True
            backtracking(nums, result, used, permutation)
            used[i] = False
            permutation.pop()


def fun(nums):
    result = []
    used = dict()
    for i in range(0, len(nums)):
        used[i] = False
    backtracking(nums, result, used, [])
    return result

print(fun([1,2,3,4]))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

运行结果:

[[1, 2, 3, 4], [1, 2, 4, 3], [1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 2, 3], [1, 4, 3, 2], [2, 1, 3, 4], [2, 1, 4, 3], [2, 3, 1, 4], [2, 3, 4, 1], [2, 4, 1, 3], [2, 4, 3, 1], [3, 1, 2, 4], [3, 1, 4, 2], [3, 2, 1, 4], [3, 2, 4, 1], [3, 4, 1, 2], [3, 4, 2, 1], [4, 1, 2, 3], [4, 1, 3, 2], [4, 2, 1, 3], [4, 2, 3, 1], [4, 3, 1, 2], [4, 3, 2, 1]]
1
编辑 (opens new window)
#回溯法
上次更新: 2023/02/16, 22:15:06
动态规划算法
Leetcode-78-子集

← 动态规划算法 Leetcode-78-子集→

最近更新
01
ESP32-网络摄像头方案
06-14
02
ESP32-PWM驱动SG90舵机
06-14
03
ESP32-实时操作系统freertos
06-14
更多文章>
Theme by Vdoing | Copyright © 2019-2025 DC Wang All right reserved | 辽公网安备 21021102001125号 | 吉ICP备20001966号-2
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式