[LeetCode]Minimum Path Sum
2014-03-14 16:06 庸男勿扰 阅读(134) 评论(0) 编辑 收藏 举报原题链接:http://oj.leetcode.com/problems/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.
题解:
这是提到基本的动态规划题,转移方程为:dp[i][j] = min(dp[i-1][j],dp[i][j-1])+a[i][j]。
1 class Solution { 2 public: 3 int minPathSum(vector<vector<int> > &grid) { 4 int m = grid.size(); 5 int n = grid[0].size(); 6 int ret; 7 int** dp = new int*[m]; 8 for(int i = 0; i < m; i++) 9 dp[i] = new int[n]; 10 11 dp[0][0] = grid[0][0]; 12 13 for(int i = 1; i < m; i++) 14 dp[i][0] = dp[i-1][0] + grid[i][0]; 15 16 for(int i = 1; i <n; i++) 17 dp[0][i] = dp[0][i-1] + grid[0][i]; 18 19 for(int i=1; i<m; i++){ 20 for(int j=1; j<n; j++){ 21 dp[i][j] = min(dp[i][j-1],dp[i-1][j])+grid[i][j]; 22 } 23 } 24 ret = dp[m-1][n-1]; 25 for(int i = 0; i < m; i++) 26 delete []dp[i]; 27 28 delete []dp; 29 30 return ret; 31 } 32 };
作者:庸男勿扰
出处:http://www.cnblogs.com/codershell
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果您觉得对您有帮助,不要忘了推荐一下哦~
出处:http://www.cnblogs.com/codershell
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果您觉得对您有帮助,不要忘了推荐一下哦~