leetcode 46. 全排列
描述:
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
# def backtrack(rest_nums=nums, now_seq=[]):
# """Version 1"""
# if len(rest_nums) == 0:
# res.append(now_seq)
# return
# for idx in range(len(rest_nums)):
# backtrack(rest_nums[:idx]+rest_nums[idx+1:], now_seq+[rest_nums[idx]])
# return
# res = []
# backtrack()
# return res
# def backtrack(now_len=0, now_seq=[]):
# """Version 2"""
# if now_len == N:
# res.append(now_seq)
# for i in range(N):
# if visited[i] == 1:
# continue
# visited[i] = 1
# backtrack(now_len+1, now_seq+[nums[i]])
# visited[i] = 0
# return
# N = len(nums)
# visited = [0]*N
# res = []
# backtrack()
# return res
# """Version Cheat"""
# return list(itertools.permutations(nums))
def swap(i,j,this=nums):
this[i],this[j] = this[j],this[i]
def backtrack(pos=0):
"""Version 3"""
if pos == N:
res.append(nums[:])
for i in range(pos, N):
swap(pos,i)
backtrack(pos+1)
swap(pos,i)
N = len(nums)
res = []
backtrack()
return res