[Leetcode] Minimum Path Sum

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.

Solution: dp

 1 public class Solution {
 2     public int minPathSum(int[][] grid) {
 3         int M=grid.length;
 4         int N=grid[0].length;
 5         int[][] dp=new int[M][N];
 6         dp[0][0]=grid[0][0];
 7         for(int i=1;i<M;++i){
 8             dp[i][0]=dp[i-1][0]+grid[i][0];
 9         }
10         for(int i=1;i<N;++i){
11             dp[0][i]=dp[0][i-1]+grid[0][i];
12         }
13         for(int i=1;i<M;++i){
14             for(int j=1;j<N;++j){
15                 dp[i][j]=Math.min(dp[i-1][j],dp[i][j-1])+grid[i][j];
16             }
17         }
18         return dp[M-1][N-1];
19     }
20 }

 

posted @ 2014-10-24 16:31  Phoebe815  阅读(126)  评论(0编辑  收藏  举报