码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Minimum Path Sum

时间:2014-09-06 05:27:22      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   使用   ar   div   问题   

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.

Note: You can only move either down or right at any point in time.

Unique Path问题相似,是一个DP问题,解决问题的方案依然是建造一个新矩阵,每个元素值是从top left到该点的最短距离。递归式可以根据这个写出来,并且一旦计算出了到该点的最短距离,就把它存起来以备其他点使用。

 1 public class Solution {
 2     public int minPathSum(int[][] grid) {
 3         int m = grid.length;
 4         int n = grid[0].length;
 5         if (m == 0 || n == 0) return 0;
 6         int[][] matrix = new int[m][n];
 7         return FindMinPath(m-1, n-1, grid, matrix);
 8     }
 9     
10     public int FindMinPath(int i, int j, int[][]grid, int[][]matrix) {
11         if (matrix[i][j] != 0) return matrix[i][j];
12         if (i == 0 && j == 0) {
13             matrix[i][j] = grid[0][0];
14             return matrix[i][j];
15         }
16         if (i == 0 && j != 0) {
17             matrix[i][j] = FindMinPath(i, j-1, grid, matrix) + grid[i][j];
18             return matrix[i][j];
19         }
20         if (i != 0 && j == 0) {
21             matrix[i][j] = FindMinPath(i-1, j, grid, matrix) + grid[i][j];
22             return matrix[i][j];
23         }
24         else {
25             matrix[i][j] = Math.min(FindMinPath(i, j-1, grid, matrix), FindMinPath(i-1, j, grid, matrix)) + grid[i][j];
26             return matrix[i][j];
27         }
28     }
29 }

 

Leetcode: Minimum Path Sum

标签:style   blog   http   color   io   使用   ar   div   问题   

原文地址:http://www.cnblogs.com/EdwardLiu/p/3958961.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!