标签:
题目:
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.(Medium)
分析:
矩阵型动态规划,dp[i][j]表示到达i,j位置的。。。。
所以本题中dp[i][j]表示到达grid[i][j]的最小和。dp[i][j] = dp[i -1][j] + dp[i][j - 1];
代码:
1 class Solution { 2 public: 3 int minPathSum(vector<vector<int>>& grid) { 4 int dp[grid.size()][grid[0].size()]; 5 dp[0][0] = grid[0][0]; 6 for (int i = 1; i < grid.size(); ++i) { 7 dp[i][0] = dp[i - 1][0] + grid[i][0]; 8 } 9 for (int i = 1; i < grid[0].size(); ++i) { 10 dp[0][i] = dp[0][i - 1] + grid[0][i]; 11 } 12 for (int i = 1; i < grid.size(); ++i) { 13 for (int j = 1; j < grid[0].size(); ++j) { 14 dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; 15 } 16 } 17 return dp[grid.size() - 1][grid[0].size() - 1]; 18 } 19 };
标签:
原文地址:http://www.cnblogs.com/wangxiaobao/p/5890673.html