标签:
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