【发布时间】:2020-09-24 08:21:59
【问题描述】:
对于insects combinatorics的实验室问题,下面是我使用树递归的解决方案:
func Paths(m int, n int) int {
length := m
width := n
var f func(int, int) int
f = func(h int, v int) int {
if h == width && v == length {
return 1
} else if h < width && v < length {
return f(h, v+1) + f(h+1, v)
} else if v < length {
return f(h, v+1)
} else if h < width {
return f(h+1, v)
} /*else { // this condition doesn't occur
return 0
}*/
} // Line 19
return f(1, 1)
}
上述解决方案不需要else块(无效),但编译器在第19行给出missing return error
上述代码如何避免missing return error?
【问题讨论】:
-
"如何避免丢失返回错误" --- 每个函数路径都应该以
return结尾。所以,为了避免它 - 你应该return一个整数。 -
一方面,条件不能发生并不明显(事实上,创建它确实发生的情况是微不足道的,例如
Paths(0, 0)):去抱怨是对的。如果你有一定的把握,重写代码使其更明显。另一方面,您确定条件中没有错误吗?您有时会将h与length进行比较,有时将其与width进行比较(反之亦然v)。在不知道您要解决的问题的情况下,这似乎是先验不可能的。 -
与您的问题无关,但没有理由这样做
return } else。只需删除其他。 -
@KonradRudolph 嘿,你是对的
h应该始终与width进行比较。查询已编辑.. 错字