LeetCode:Minumus Path Sum(矩阵路线的元素最小值DP)

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.

 
 思路:与求两个字符串的最长公共子序列的长度思路一致。
状态转移方程为:dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i-1][j-1];(Ps:i j 从1开始 防止越界问题)

 

 1 class Solution {
 2 public:
 3     int minPathSum(vector<vector<int>>& grid) {
 4         
 5        int m=grid.size();
 6        int n=grid[0].size();
 7        
 8        vector<vector<int> > dp(m+1, vector<int>(n+1, INT_MAX));
 9         
10        for(int i=1;i<=m;i++)
11         for(int j=1;j<=n;j++)
12         {
13             if(i==1&&j==1)
14                 dp[i][j]=grid[i-1][j-1];
15             else              
17                 dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i-1][j-1];
18         }
19         
20         return dp[m][n];
21             
22     }
23 };

 

posted @ 2015-08-03 15:44  尾巴草  阅读(228)  评论(0编辑  收藏  举报