def solve2(lst, bound):
max_length = bound // min(lst)
for n in range(1, max_length+1):
for c in itertools.combinations_with_replacement(lst,n):
if sum(c) <= bound:
print('+'.join(map(str, c)))
solve2([1,2,3], 10)
# code for python3
from itertools import combinations
def solve(lst, upperbound):
candidates = []
for n in lst:
for count in range(upperbound//n):
candidates.append(n)
allcomb = set()
for l in range(1, len(candidates)+1):
for comb in combinations(candidates, l):
if not comb in allcomb:
allcomb.add(comb)
if sum(comb) <= upperbound:
print('+'.join([str(n)for n in comb]))
solve([1,2,3], 10)
通过itertools.combinations_with_replacement我们写短一点的代码:
假设该问题符合下列假设:
列表内元素可重复使用
只要是能满足小于等于上限值的组合都可接受, 就算远小于上限值甚至是零也可以
以下是暴力法:
我回答过的问题: Python-QA