题目46:全排列
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
代码实现1
- 回溯法的解题步骤与例子解析 - 若明天不见 - CSDN博客 https://blog.csdn.net/why_still_confused/article/details/51713415
- 五大常用算法总结 - 来自师范的学渣 - CSDN博客 https://blog.csdn.net/qq_40788630/article/details/79503946
- 基础算法系列总结:回溯算法(解火力网问题) - 大熊先生|互联网后端技术 - 博客园 https://www.cnblogs.com/Creator/archive/2011/05/20/2052341.html
class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def backtrack(first=0):
if first == n:
output.append(nums[:])
for i in range(first, n):
nums[first], nums[i] = nums[i], nums[first]
backtrack(first + 1)
nums[first], nums[i] = nums[i], nums[first]
n = len(nums)
output = []
backtrack()
return output
代码实现2
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
from itertools import permutations
return list(permutations(nums))
参考&学习代码:回溯法
代码实现1
class Solution:
def permute(self, nums):
res = []
def backtrack(nums, tmp):
if not nums:
res.append(tmp)
return
for i in range(len(nums)):
backtrack(nums[:i] + nums[i+1:], tmp + [nums[i]])
backtrack(nums, [])
return res
代码实现2
每次固定第一个数字递归地排列数组剩余部分
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
list = []
for i, n in enumerate(nums):
for sub in self.permute(nums[:i] + nums[i + 1:]):
list.append([n] + sub)
return list or [nums]