46. 全排列
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
解法1
class Solution:
def permute(self, nums):
if len(nums) <= 1:
return [nums]
res = [[nums[0]]]
index = 1
while index < len(nums):
tmp = []
for each in res:
for i in range(index+1):
tmp.append(each[:i]+[nums[index]]+each[i:])
res = tmp
index += 1
return res
解法2
class Solution:
def permute(self, nums):
if len(nums) <= 1:
return [nums]
res = []
perms = self.permute(nums[1:])
for each in perms:
for i in range(len(each)+1):
p = each[:i]+[nums[0]]+each[i:]
res.append(p)
return res
解法3
用itertools库的permutations
函数.
import itertools
class Solution:
def permute(self, nums):
return list(itertools.permutations(nums))
基本思路都是用DFS算法+交换数字的方式。还有更多全排列的题请参考:
https://blog.csdn.net/jacky_chenjp/article/details/66477538