【发布时间】:2019-04-15 08:11:07
【问题描述】:
给定一个数组大小 n 和一个正数 max(max 表示我们可以用来放置在数组中的数字的范围)。
我想计算可以在数组中放置多少个已排序数字的组合。
例如:
如果n = 3, max = 2.(我们可以使用的唯一数字是 1/2,因为最大值是 2)所以排序数组有 4 种组合
1. {1,1,1}
2. {1,1,2}
3. {1,2,2}
4. {2,2,2}
我编写了一些代码并成功通过了这个特定的示例,但是max > 2 没有返回正确答案的任何其他示例。
我发现的问题是,当递归到达最后一个索引时,它不会尝试第三个数字,而是折回。
我的代码:
private static int howManySorted(int n, int max, int index, int numToMax, int prevNum) {
// If the value is bigger then max return 0
if(numToMax > max) {
return 0;
}
if (numToMax < prevNum) {
return 0;
}
//If Index reached the end of the array return 1
if(index == n) {
return 1;
}
int sortTwo = howManySorted(n, max, index+1, numToMax, numToMax);
int sortOne = howManySorted(n, max, index+1, numToMax+1, numToMax);
return ((sortOne+sortTwo));
}
public static int howManySorted(int n, int max) {
return howManySorted(n, max, 0, 1, 0);
}
【问题讨论】:
-
好奇:
numToMax < prevNum什么时候会是真的? -
你在代码中只能递归两次,即下一个数只能和前一个相同或高一个,这意味着对于
max > 2你不会找到1,1,5这样的解决方案,因为这是 4 的跳跃。 -
是的,我知道这就是我在此处发帖的原因(:
-
仅供参考: 参数
index是多余的。在递归调用中,不要将index从0计数到n,而是将n倒数到0。 -
所以在递归调用周围添加一个循环,从
numToMax循环到max。 --- 另外,鉴于我的第一条评论,参数prevNum是多余的。摆脱它。