Skip to content

Commit 5f8026f

Browse files
committed
feat: add cache
1 parent a771831 commit 5f8026f

File tree

1 file changed

+10
-4
lines changed
  • min_cost_climbing_stairs/src

1 file changed

+10
-4
lines changed

min_cost_climbing_stairs/src/lib.rs

+10-4
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,22 @@
11
pub struct Solution {}
22

33
impl Solution {
4-
fn min_cost_to_step(cost: &Vec<i32>, i: usize) -> i32 {
4+
fn min_cost_to_step(cost: &Vec<i32>, cache: &mut Vec<Option<i32>>, i: usize) -> i32 {
55
if i < 2 {
66
return 0;
77
}
8-
(Self::min_cost_to_step(cost, i - 1) + cost[i - 1])
9-
.min(Self::min_cost_to_step(cost, i - 2) + cost[i - 2])
8+
if let Some(res) = cache[i] {
9+
return res;
10+
}
11+
let res = (Self::min_cost_to_step(cost, cache, i - 1) + cost[i - 1])
12+
.min(Self::min_cost_to_step(cost, cache, i - 2) + cost[i - 2]);
13+
cache[i] = Some(res);
14+
res
1015
}
1116

1217
pub fn min_cost_climbing_stairs(cost: Vec<i32>) -> i32 {
13-
Self::min_cost_to_step(&cost, cost.len())
18+
let mut cache = vec![None; cost.len() + 1];
19+
Self::min_cost_to_step(&cost, &mut cache, cost.len())
1420
}
1521
}
1622

0 commit comments

Comments
 (0)