我是 Rust 新手,但作为 Haskell 的粉丝,我非常欣赏这种方式match
在 Rust 中工作。现在,我面临着一种罕见的情况,我确实需要失败——从某种意义上说,我希望执行几个重叠案例的所有匹配案例。这有效:
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 中是否惯用,或者是否有更好的方法。
上下文是一个问题破解编码面试:“一个孩子正在跑上楼梯,n步,一次可以跳 1 步、2 步或 3 步。实施一种方法来计算孩子有多少种可能的方式跑上楼梯。”
基于tribonacci序列的定义我发现你可以用更简洁的方式来写它,如下所示:
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
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)