思路:回溯算法
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
ans,path = [],[]
n = len(nums)
if n==0:return [[]]
def helper(nums,depth):
if depth==n:
ans.append(path[:])
return
for i in range(n):
if not nums[i] in path: # 条件,不能使用重复元素
path.append(nums[i])
helper(nums,depth+1)
path.pop()
helper(nums,0)
return ans
思路2:
使用标记数组,不使用已使用的元素。
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
ans,path = [],[]
n = len(nums)
flag = [0 for _ in range(n)] # 标记数组 0:未使用 1:已使用
if n==0:return [[]]
def helper(nums,depth):
if depth==n:
ans.append(path[:])
return
for i in range(n):
if flag[i]==0:
path.append(nums[i])
flag[i]=1
helper(nums,depth+1)
flag[i]=0
path.pop()
helper(nums,0)
return ans
思路3:库函数
import itertools
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
return list(itertools.permutations(nums)) # 返回全排列 包括重复排列