File tree 1 file changed +38
-0
lines changed
Lintcode/src/chapter4_DynamicProgrammingI
1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ package chapter4_DynamicProgrammingI ;
2
+
3
+ /**
4
+ * Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right
5
+ * which minimizes the sum of all numbers along its path.
6
+ *
7
+ * Notice
8
+ *
9
+ * You can only move either down or right at any point in time.
10
+ */
11
+ public class MinimumPathSum {
12
+
13
+ /**
14
+ * @param grid: a list of lists of integers.
15
+ * @return: An integer, minimizes the sum of all numbers along its path
16
+ */
17
+ public int minPathSum (int [][] grid ) {
18
+ // write your code here
19
+ if (grid == null || grid .length == 0 ) return 0 ;
20
+ int m = grid .length , n = grid [0 ].length ;
21
+ int [][] paths = new int [m ][n ];
22
+
23
+ paths [0 ][0 ] = grid [0 ][0 ];
24
+
25
+ for (int i = 1 ; i < m ; i ++) paths [i ][0 ] = grid [i ][0 ] + paths [i -1 ][0 ];
26
+
27
+ for (int j = 1 ; j < n ; j ++) paths [0 ][j ] = grid [0 ][j ] + paths [0 ][j -1 ];
28
+
29
+ for (int i = 1 ; i < m ; i ++){
30
+ for (int j = 1 ; j < n ; j ++){
31
+ paths [i ][j ] = grid [i ][j ] + Math .min (paths [i -1 ][j ], paths [i ][j -1 ]);
32
+ }
33
+ }
34
+
35
+ return paths [m -1 ][n -1 ];
36
+ }
37
+
38
+ }
You can’t perform that action at this time.
0 commit comments