我使用itertools
combinations_with_replacement
创建了一个生成器,它返回3个正整数的所有组合,这些正整数的总和为n:
def combinations(n):
for combo in combinations_with_replacement([i for i in range(1,n+1)],3):
if sum(combo) == n:
yield(combo)
例如combinations(7)
返回(1, 1, 5) (1, 2, 4) (1, 3, 3) (2, 2, 3)
不幸的是,当n的值较大时,这很快就会变得非常缓慢。有没有一种更有效的替代方法?我尝试过使用for循环,尽管每次我都会得到重复的组合。
提前谢谢!你知道吗
您可以使用递归函数来实现这一点:选择一个合适的数字;然后对剩余的大小和总数进行递归。你知道吗
输出:
简言之,不,这是一个非常复杂的算法,很快就会归结为
O(n ^ 3)
“算法”本身可能不会比
O(n ^ 2)
更有效,但您可以很容易地将其更改为O(n ^ 2)
。你知道吗希望这至少有点帮助。你知道吗
您不必获得三个数字的所有组合。你可以得到两个数的组合,你就知道第三个数是什么了。你知道吗
这要快得多:
相关问题 更多 >
编程相关推荐