rust - Rust 中 tribonacci 序列的惯用实现

标签 rust fibonacci idioms fall-through

我是 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/

相关文章:

r - 根据键在数据框中汇总值

Rust 错误传播在传播级别上具有不同类型

rust - 如何避免在特征实现中两次指定相同的类型?

C++ 段错误,为什么使用 "long long"我没有得到答案?

scala - 从 Scala 中的 VM 参数获取 bool 值

c++ - 从字符串c++中删除非字母字符

rust - 如何在文档测试中构建代码但不运行它?

algorithm - 有没有更好的方法来使用图像 0.18 crate 实现中点圆算法?

C 打印第一个百万斐波那契数

command-line - 从控制台加载参数