排列
def permute(nums):
result = []
def backtrack(track, toSelect):
if len(track) == len(nums):
result.append(track)
return
for i in toSelect:
# 构造 可选择列表
tmp = toSelect
tmp.remove(i)
# 选择
track.append(i)
backtrack(track, tmp)
# 撤销选择
track.pop()
backtrack(nums)
return result
组合
def combine(nums, n):
result = []
def backtrack(track, toSelect):
if len(track) == n:
# 组合去重
tmp = track[:]
sorted(tmp)
if tmp not in result:
result.append(tmp)
return
for i in toSelect:
# 构造 可选择列表
tmp = toSelect
tmp.remove(i)
# 选择
track.append(i)
backtrack(track, tmp)
# 撤销选择
track.pop()
backtrack(nums, n)
return result