Created
January 26, 2021 08:02
-
-
Save jargnar/f01ef19c49fd7dada3dd02abbd78b764 to your computer and use it in GitHub Desktop.
Climbing Stairs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::HashMap; | |
impl Solution { | |
pub fn fib(n: i32, cache: &mut HashMap<i32, i32>) -> i32 { | |
if n <= 2 { return n; } | |
else if !cache.contains_key(&(n-1)) && !cache.contains_key(&(n-2)) { | |
let a = Self::fib(n - 1, cache); | |
let b = Self::fib(n - 2, cache); | |
cache.insert(n - 1, a); | |
cache.insert(n - 2, b); | |
} | |
return *cache.get(&(n - 1)).unwrap() + *cache.get(&(n - 2)).unwrap(); | |
} | |
pub fn climb_stairs(n: i32) -> i32 { | |
Self::fib(n, &mut HashMap::new()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://leetcode.com/problems/climbing-stairs/