🦀

ALDS1_10_A Fibonacci Number by Rust

2022/04/11に公開

code

単純な再帰よりも計算が省ける。これがDP。

use std::io;

fn read<T: std::str::FromStr>() -> Vec<T> {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    buf.trim().split(' ').flat_map(str::parse).collect()
}

fn main() {
    let n = read::<usize>()[0];

    let mut v:Vec<i128> = vec![0;100];
    v[0] = 1;
    v[1] = 1;

    for i in 2..=n {
        v[i] = v[i-1] + v[i-2];
    }
    println!("{}",v[n])
}

Discussion