给定一个整数数组,求它的全排列。
思路一:
使用Python的库函数itertoos.permutations
。
from itertools import permutations
from itertools import permutations
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
return list(permutations(nums)
思路二:
使用DFS算法。
设输入的数组为[1, 2, 3]
,具体的排列过程如下表所示:
class Solution(object):
def __init__(self):
self.res = []
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
self.helper(nums, [])
return self.res
def helper(self, nums, path):
if not nums:
self.res.append(path)
for i in range(len(nums)):
self.helper(nums[:i]+nums[i+1:], path+[nums[i]])
参考链接:https://blog.csdn.net/fuxuemingzhu/article/details/79363903