题目
思路
DFS,把结果加入到返回list的时候注意去重。
代码
class Solution:
"""
@param: num: Given the candidate numbers
@param: target: Given the target number
@return: All the combinations that sum to target
"""
def __init__(self):
self.res_list = []
def dfs(self, num, target, startIndex, num_list):
if target < 0: return False
if target == 0:
if num_list not in self.res_list:
self.res_list.append(num_list[:])
return True
for i in range(startIndex + 1, len(num)):
num_list.append(num[i])
self.dfs(num, target - num[i], i, num_list)
num_list.pop(-1)
def combinationSum2(self, num, target):
# write your code here
num.sort()
self.dfs(num, target, -1, [])
return self.res_list