Coding中等
LC46 全排列
回溯模板;
简要回答
回溯模板;used[] 数组标已用;进出递归时成对地"做选择/撤销选择"。
标准答案
考察点:回溯模板;used[] 数组标已用;进出递归时成对地"做选择/撤销选择"。
实现:
def permute(nums): n = len(nums)
res = []
used = [False] * n
path = []
def dfs():
if len(path) == n:
res.append(path[:]) # 收集时必须拷贝快照
return
for i in range(n):
if used[i]:
continue
# 做选择
used[i] = True
path.append(nums[i])
dfs()
# 撤销选择(成对出现)
path.pop()
used[i] = False
dfs()
return res
常见错误
- 收集
res.append(path)而非path[:]致引用共享被改污染 - 忘撤销
- LC47 去重时条件方向反(应在
not used[i-1]时跳过同层重复枝)。