【发布时间】:2020-02-20 21:43:57
【问题描述】:
我正在处理一项任务,现在我有一个数字我想知道有多少种方法可以使用 2,3,6 使用加法来达到这个数字,并且我可以尽可能多次地使用一个数字。
第一个例子:
Given number is 6
There are 3 ways to reach to this number:
2 +2 + 2 = 2*3
3 + 3 = 3*2
6
第二个例子:
Given number is 5
There are 2 ways to reach to this number:
2+3
3+2 (order matters here)
我在this link 的帮助下想出了以下代码:
static int count(int n) {
// table[i] will store count of solutions for
// value i.
int table[] = new int[n + 1], i;
// Base case (If given value is 0)
table[0] = 1;
// One by one consider given 3
// moves and update the table[]
// values after the index greater
// than or equal to the value of
// the picked move
for (i = 2; i <= n; i++)
table[i] += table[i - 2];
for (i = 3; i <= n; i++)
table[i] += table[i - 3];
for (i = 6; i <= n; i++)
table[i] += table[i - 6];
return table[n];
}
此代码仅适用于第一个示例,但不适用于第二个示例,因为程序返回 1 而不是 2。
如何解决这个问题?
【问题讨论】:
-
你说只使用了 2、3 和 6,但第一个例子是
6 * 1,所以你使用了1,但你说这个例子是正确的? -
@Nexevis,基本上 6* 1 只不过是使用 6 本身,所以正确。 2*3 也不过是 2+2+2,我会更新我的问题以避免混淆。
-
所以基本上你只需要用这 3 个数字加起来就可以达到这个数字,但是你想用多少次就用多少次?
-
定义“到达”一个数字。在您的第一个示例中,
(2^3)-2是达到 6 的另一种方式。 -
@Nexevis,是的,只添加了多少次,我会更新它