首页 > 其他 > 详细

[leetcode] Minimum Path Sum

时间:2014-05-01 07:53:42      阅读:364      评论:0      收藏:0      [点我收藏+]

思路很简单,就是存储之前运算的结果,然后递归

 

class Solution {
public:
int** dp;

int get_min_sum(vector<vector<int> > &grid, int m, int n)
{
if (dp[m][n] != -1)
return dp[m][n];
if (m == 0 && n == 0)
return grid[m][n];

if (dp[m-1][n] == -1)
dp[m-1][n] = get_min_sum(grid, m-1, n);
if (dp[m][n-1] == -1)
dp[m][n-1] = get_min_sum(grid, m, n-1);

dp[m][n] = min(dp[m-1][n] + grid[m][n], dp[m][n-1] + grid[m][n]);

return dp[m][n];
}

int minPathSum(vector<vector<int> > &grid) {
int m = grid.size();
int n = 0;
if (!grid.empty() && !grid[0].empty())
{
n = grid[0].size();
} else
return 0;

dp = (int**)malloc(sizeof(int*)*(m+1));
for (int i = 0; i < m+1; ++i)
dp[i] = (int*)malloc(sizeof(int)*(n+1));
for (int i = 0; i < m+1; ++i)
memset(dp[i], -1, sizeof(int)*(n+1));

dp[0][0] = grid[0][0];

for (int i = 1; i < n; ++i)
dp[0][i] = dp[0][i-1] + grid[0][i];
for (int i = 1; i < m; ++i)
dp[i][0] = dp[i-1][0] + grid[i][0];

int res = get_min_sum(grid, m-1, n-1);

for (int i = 0; i < m+1; ++i)
delete [] dp[i];

delete [] dp;

return res;
}
};

[leetcode] Minimum Path Sum,布布扣,bubuko.com

[leetcode] Minimum Path Sum

原文:http://www.cnblogs.com/andy071001/p/3701826.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!