Skip to content

Commit

Permalink
P67: bottom-to-top dynamic programming.
Browse files Browse the repository at this point in the history
  • Loading branch information
tfpf committed Feb 11, 2024
1 parent 0e7eecb commit 6b671e9
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 39 deletions.
1 change: 0 additions & 1 deletion src/solutions/maximum_path_sum_i.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ pub fn solve() -> i64 {
triangle[row][col] += std::cmp::max(triangle[row + 1][col], triangle[row + 1][col + 1]);
}
}

let result = triangle[0][0];

assert_eq!(result, 1074);
Expand Down
46 changes: 8 additions & 38 deletions src/solutions/maximum_path_sum_ii.rs
Original file line number Diff line number Diff line change
@@ -1,50 +1,20 @@
use std::io::BufRead;

struct CacheMap {
map: std::collections::HashMap<(usize, usize), i32>,
triangle: Vec<Vec<i32>>,
}
impl CacheMap {
fn new(triangle: Vec<Vec<i32>>) -> CacheMap {
CacheMap {
map: std::collections::HashMap::new(),
triangle,
}
}
/// Find the maximum path sum to the bottom, starting from the given row
/// and column indices.
///
/// * `key` - Tuple of row and column indices.
///
/// -> Maximum path sum.
fn get(&mut self, key: (usize, usize)) -> i32 {
let (row, col) = key;
if row >= self.triangle.len() {
return 0;
}
match self.map.get(&key) {
Some(&value) => value,
None => {
let left = self.get((row + 1, col));
let right = self.get((row + 1, col + 1));
let value = self.triangle[row][col] + std::cmp::max(left, right);
self.map.insert(key, value);
value
}
}
}
}

pub fn solve() -> i64 {
let fhandle = std::fs::File::open("res/maximum_path_sum_ii.txt").unwrap();
let reader = std::io::BufReader::new(fhandle);
let triangle: Vec<Vec<i32>> = reader
let mut triangle: Vec<Vec<i32>> = reader
.lines()
.map(|line| line.unwrap().split(' ').map(|s| s.parse().unwrap()).collect())
.collect();

let mut cache_map = CacheMap::new(triangle);
let result = cache_map.get((0, 0));
// Bottom-up dynamic programming.
for row in (0..triangle.len()).rev().skip(1) {
for col in 0..triangle[row].len() {
triangle[row][col] += std::cmp::max(triangle[row + 1][col], triangle[row + 1][col + 1]);
}
}
let result = triangle[0][0];

assert_eq!(result, 7273);
result as i64
Expand Down

0 comments on commit 6b671e9

Please sign in to comment.