当在更深层的数,一定不能包括在之前的出现的数的时候,用visited数组来标记
回溯时,退栈,状态重置
&
去重:hash表、排序sort
因为是组合问题,所以我们按顺序读字符,就不需要设置 used 数组;
class Salution:
def dealwith(self, nums, target):
size = len(nums)
if size == 0: return []
res = []
path = []
nums.sort()
def dfs(begin, target):
# 退出条件
if target == 0:
return res.append(path[:])
for i in range(begin, size):
if i > begin and nums[i] == nums[i-1]:
continue
result = target - nums[i]
if result < 0:
break
path.append(nums[i])
dfs(i+1, result)
path.pop()
dfs(0, target)
return res