0046-全排列

给定一个不含重复数字的数组 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)
链接:https://leetcode-cn.com/problems/permutations

参考:

python

# 0046.全排列
class Solution:
def permute(self, nums: [int]) -> [[int]]:
res = []
path = []
used = [] # 存放已经使用过的数字
def track(nums, used):
if len(path) == len(nums):
return res.append(path[:])
for i in range(0, len(nums)):
if nums[i] in used:
continue # used中已收录,跳过
path.append(nums[i])
used.append(nums[i])
track(nums, used)
used.pop()
path.pop()
track(nums, used)
return res
# 不使用used记录使用的元素
class Solution:
def permute(self, nums: [int]) -> [[int]]:
res = []
path = []
def track(nums):
if len(path) == len(nums):
return res.append(path[:])
for i in range(0, len(nums)):
if nums[i] in path:
continue
path.append(nums[i])
track(nums)
path.pop()
track(nums)
return res

golang

package backTrack
var res [][]int
func permute(nums []int) [][]int {
res = [][]int{}
track(nums, len(nums), []int{})
return res
}
func track(nums []int, length int, path []int) {
if len(nums) == 0 {
p := make([]int, len(path))
copy(p, path)
res = append(res, p)
}
for i:=0;i<length;i++ {
cur := nums[i]
path = append(path, cur)
nums = append(nums[:i], nums[i+1:]...)
track(nums, len(nums), path)
nums = append(nums[:i], append([]int{}, nums[i:]...)...)
path = path[:len(path)-1]
}
}

posted on   进击的davis  阅读(36)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示