Skip to content

Commit bda93ff

Browse files
author
applewjg
committed
MinimumPathSum
Change-Id: If5ffcb57ecfdab8d54a0fca6fba7d11dea0e1a76
1 parent f651cef commit bda93ff

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

MinimumPathSum.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 26, 2014
4+
Problem: Minimum Path Sum
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/minimum-path-sum/
7+
Notes:
8+
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right
9+
which minimizes the sum of all numbers along its path.
10+
Note: You can only move either down or right at any point in time.
11+
12+
Solution: Dynamic Programming. Space O(N).
13+
*/
14+
public class Solution {
15+
public int minPathSum(int[][] grid) {
16+
if (grid.length == 0) return Integer.MIN_VALUE;
17+
int M = grid.length, N = grid[0].length;
18+
int[] dp = new int[N];
19+
dp[0] = grid[0][0];
20+
for (int i = 1; i < N; ++i)
21+
dp[i] = grid[0][i] + dp[i-1];
22+
23+
for (int i = 1; i < M; ++i)
24+
{
25+
dp[0] += grid[i][0];
26+
for (int j = 1; j < N; ++j)
27+
dp[j] = Math.min(dp[j-1], dp[j]) + grid[i][j];
28+
}
29+
30+
return dp[N-1];
31+
}
32+
}

0 commit comments

Comments
 (0)