【发布时间】:2020-12-28 12:38:00
【问题描述】:
长度为 N 的可重复组合有多少个?
如 [1,3,5,10],N = 4。
还有
[1,1,1,1] -> sum is 4
[1,1,1,3] -> sum is 6
...
[10,10,10,10] -> sum is 40
我执行回溯算法。通过python3
res = set()
n = 4
def backtrack(k, path):
if len(path) == n:
res.add(sum(path))
return
backtrack(k+1, path+[1])
backtrack(k+1, path+[3])
backtrack(k+1, path+[5])
backtrack(k+1, path+[10])
return
backtrack(0, list())
有没有更有效的解决方案?
【问题讨论】:
-
那是 Python,不是吗?考虑标记它以吸引更多潜在有用的用户。
标签: math combinations backtracking recursive-backtracking