我是 Rust 的新手,但作为 Haskell 的粉丝,我非常欣赏 match
在 Rust 中的工作方式。现在我面临着我确实需要 fall-through 的罕见情况——从某种意义上说,我希望执行几个重叠案例的所有匹配案例。这有效:
fn options(stairs: i32) -> i32 {
if stairs == 0 {
return 1;
}
let mut count: i32 = 0;
if stairs >= 1 {
count += options(stairs - 1);
}
if stairs >= 2 {
count += options(stairs - 2);
}
if stairs >= 3 {
count += options(stairs - 3);
}
count
}
我的问题是这在 Rust 中是惯用的还是有更好的方法。
上下文是Cracking the Coding Interview中的一个问题:“一个 child 正在用n步跑上楼梯,可以跳1步、2步或一次3个步骤。实现一种方法来计算 child 可以跑上楼梯的可能方式。”
最佳答案
基于definition of the tribonacci sequence我发现您可以像这样以更简洁的方式编写它:
fn options(stairs: i32) -> i32 {
match stairs {
0 => 0,
1 => 1,
2 => 1,
3 => 2,
_ => options(stairs - 1) + options(stairs - 2) + options(stairs - 3)
}
}
我还建议将函数定义更改为仅接受正整数,例如u32
。
关于rust - Rust 中 tribonacci 序列的惯用实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56802007/