Skip to content

Commit ebee824

Browse files
committed
solve #64
1 parent c26274b commit ebee824

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,4 @@ mod n0060_permutation_sequence;
6464
mod n0061_rotate_list;
6565
mod n0062_unique_paths;
6666
mod n0063_unique_paths_ii;
67+
mod n0064_minimum_path_sum;

src/n0064_minimum_path_sum.rs

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/**
2+
* [64] Minimum Path Sum
3+
*
4+
* Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
5+
*
6+
* Note: You can only move either down or right at any point in time.
7+
*
8+
* Example:
9+
*
10+
*
11+
* Input:
12+
* [
13+
* [1,3,1],
14+
* [1,5,1],
15+
* [4,2,1]
16+
* ]
17+
* Output: 7
18+
* Explanation: Because the path 1→3→1→1→1 minimizes the sum.
19+
*
20+
*
21+
*/
22+
pub struct Solution {}
23+
24+
// submission codes start here
25+
26+
impl Solution {
27+
pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 {
28+
let (height, width) = (grid.len(), grid[0].len());
29+
let mut grid = grid;
30+
let mut step = 1;
31+
while step <= height + width - 2 {
32+
for x in 0..(step+1) {
33+
let y = step - x;
34+
if x >= height || y >= width { continue }
35+
if x < 1 {
36+
grid[x][y] += grid[x][y-1];
37+
} else if y < 1 {
38+
grid[x][y] += grid[x-1][y];
39+
} else {
40+
grid[x][y] += i32::min(grid[x][y-1], grid[x-1][y]);
41+
}
42+
}
43+
step += 1;
44+
}
45+
grid[height-1][width-1]
46+
}
47+
}
48+
49+
// submission codes end
50+
51+
#[cfg(test)]
52+
mod tests {
53+
use super::*;
54+
55+
#[test]
56+
fn test_64() {
57+
assert_eq!(
58+
Solution::min_path_sum(vec![vec![2]]),
59+
2
60+
);
61+
assert_eq!(
62+
Solution::min_path_sum(
63+
vec![
64+
vec![1,3,1],
65+
vec![1,5,1],
66+
vec![4,2,1],
67+
]),
68+
7
69+
);
70+
assert_eq!(
71+
Solution::min_path_sum(
72+
vec![
73+
vec![1,3,1],
74+
]),
75+
5
76+
);
77+
}
78+
}

0 commit comments

Comments
 (0)