含重复数字
def comb2(candidates, t):
result = []
lst = []
candidates.sort()
comb2_helper(result, lst, candidates, 0)
for exp in result:
if sum(exp) == t:
print(exp)
def comb2_helper(result, lst, candidates, pos):
result.append(lst[:])
for i in range(pos, len(candidates)):
if (i != 0 and candidates[i] == candidates[i - 1]):
continue
lst.append(candidates[i])
comb2_helper(result, lst, candidates, i + 1)
lst.pop()
if __name__ == '__main__':
candidates = [10, 1, 2, 7, 6, 1, 5]
t = 8
comb2(candidates, t)
运行结果
[1, 2, 5]
[1, 7]
[2, 6]
不含重复数字
def comb2(candidates, t):
result = []
lst = []
comb2_helper(result, lst, candidates, 0)
for exp in result:
if sum(exp) == t:
print(exp)
def comb2_helper(result, lst, candidates, pos):
result.append(lst[:])
for i in range(pos, len(candidates)):
lst.append(candidates[i])
comb2_helper(result, lst, candidates, i + 1)
lst.pop()
if __name__ == '__main__':
candidates = [10, 1, 2, 7, 6, 5]
t = 8
comb2(candidates, t)
运行结果
[1, 2, 5]
[1, 7]
[2, 6]