Skip to content

Commit 6b5d073

Browse files
committed
feat: add cache
1 parent d99c0cb commit 6b5d073

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

jump_game_vi/src/lib.rs

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,25 @@
11
pub struct Solution {}
22

33
impl Solution {
4-
fn max_res(nums: &Vec<i32>, i: usize, k: usize) -> i32 {
5-
let res = if i >= nums.len() {
6-
0
7-
} else {
8-
nums[i]
9-
+ (1..=k)
10-
.map(|x| Self::max_res(nums, i + x, k))
11-
.max()
12-
.unwrap()
13-
};
4+
fn max_res(nums: &Vec<i32>, i: usize, k: usize, cache: &mut Vec<Option<i32>>) -> i32 {
5+
if i >= nums.len() {
6+
return 0;
7+
}
8+
if let Some(res) = cache[i] {
9+
return res;
10+
}
11+
let res = nums[i]
12+
+ (1..=k)
13+
.map(|x| Self::max_res(nums, i + x, k, cache))
14+
.max()
15+
.unwrap();
16+
cache[i] = Some(res);
1417
res
1518
}
1619

1720
pub fn max_result(nums: Vec<i32>, k: i32) -> i32 {
18-
Self::max_res(&nums, 0, k as usize)
21+
let mut cache = vec![None; nums.len() + 2];
22+
Self::max_res(&nums, 0, k as usize, &mut cache)
1923
}
2024
}
2125

0 commit comments

Comments
 (0)