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

[leetcode] Minimum Path Sum

时间:2014-05-01 07:54:47      阅读:330      评论:0      收藏:0      [点我收藏+]

标签:class   c   code   t   size   sp   get   int   re   set   amp   

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

 

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

标签:class   c   code   t   size   sp   get   int   re   set   amp   

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

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