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

LeetCode – Refresh – Minimum Path Sum

时间:2015-03-21 08:35:36      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

Simple DP, but notes:

1. initialize the array not only for dp[i] += dp[i-1], but also dp[i] += dp[i-1] + grid[i][0];

2. Clear that we are using one dimensional vector to record the sum.

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

 

LeetCode – Refresh – Minimum Path Sum

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4355107.html

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