如何计算与[1,n]的组合数量,使组合总和等于n?
when n = 1
S(1) = 1;
when n = 2, there are two combinations
2 = 2
2 = 1 + 1
S(2) = 2;
when n = 3, there are 3
3 = 3
3 = 1 + 1 + 1
3 = 1 + 2
S(3) = 3
4 = 4
4 = 1 + 1 + 1 + 1
4 = 2 + 1 + 1
4 = 2 + 2
4 = 3 + 1
S(4) = 5
…………
使用n< = 1000,如何计算s(n)?我提出了一个蛮力的DFS解决方案,这是Python中的代码:
class S1:
def __init__(self):
self.cnt = 1
def dfs(self, begin, n, remain):
if n == 1: return
if remain == 0:
self.cnt += 1
return
if remain < 0:
return
for i in range(begin, n):
self.dfs(i, n, remain - i)
还有其他一些不使用递归的方法,并且时间复杂较小?
when n = 1
S(1) = 1;
when n = 2, there are two combinations
2 = 2
2 = 1 + 1
S(2) = 2;
when n = 3, there are 3
3 = 3
3 = 1 + 1 + 1
3 = 1 + 2
S(3) = 3
4 = 4
4 = 1 + 1 + 1 + 1
4 = 2 + 1 + 1
4 = 2 + 2
4 = 3 + 1
S(4) = 5
…………
With n <= 1000, how to compute S(n)? I came out with a brute-force dfs solution, here is the code in python:
class S1:
def __init__(self):
self.cnt = 1
def dfs(self, begin, n, remain):
if n == 1: return
if remain == 0:
self.cnt += 1
return
if remain < 0:
return
for i in range(begin, n):
self.dfs(i, n, remain - i)
Is there some other ways not using recursion and have smaller time complexity to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决方案包括定义函数
f(s,d)
,对应于sums
的组合数,最大数字等于或小于> D
。然后,我们可以使用递归关系的
第一项
f(s,d-1)
对应于所有术语较少或等于d-1
的组合,第二个术语f(SD,d)
对应于至少一个元素等于d
的情况。必须照顾一些特殊的价值:
这可以以迭代方式实现。这可以以递归方式等效地实现。但是,在后来的情况下,重要的是要使用记忆以避免几次计算相同的值。
最终答案等于
总复杂性是O(n^2),对于最大尺寸
n = 1000
,这应该足够。接下来是在C ++中实现,以说明算法。例如,对于
n = 1000
,该解决方案大约在10 ms中提供。A solution consists in defining a function
f(s, d)
, corresponding to the number of combinations of sums
, with a maximum digit equal to or less thand
.Then, we can use the recursive relationship
The first term
f(s, d-1)
corresponds to combinations with all terms less or equal tod-1
, and the second termf(s-d, d)
corresponds to the case where at least one element is equal tod
.One must take care of some special values:
This can be implemented in an iterative way. This can be implemented equivalently in a recursive way. However, in the later case, it is important to use memorization in order to avoid calculating the same value several times.
The final answer is equal to
The total complexity is O(n^2), which should be enough for a maximum size
n = 1000
.What follows is an implementation in C++ to illustrate the algorithm. For
n = 1000
for example, the solution is provided in about 10 ms.