leetcode 64. Minimum Path Sum

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.

Example:

Input:
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.

还是一道动态规划问题,由于只能向右或向下走,所以只用考虑一个点的上点和左点,从这两个点中找到承载的较小的数字和再加上当前点的数值即为最小数字之和
class Solution {
public:
	int minPathSum(vector<vector<int>>& obstacleGrid) {
		if (obstacleGrid.empty() ||
			obstacleGrid[0].empty())
		{
			return 0;
		}
		int h = obstacleGrid.size();        //行
		int l = obstacleGrid[0].size();     //列


		vector<vector<int>> dp(h);
		for (int i = 0; i < dp.size(); i++)
		{
			dp[i].resize(l);
		}

		dp[0][0] = obstacleGrid[0][0];
		for (int i = 1; i < h; i++)
		{
			dp[i][0] = obstacleGrid[i][0]+dp[i-1][0];
		}
		for (int j = 1; j < l; j++)
		{
			dp[0][j] = obstacleGrid[0][j]+dp[0][j-1];
		}

		for (int k = 1; k < h; k++)
		{
			for (int p = 1; p < l; p++)
			{
				dp[k][p] = (dp[k][p-1]>=dp[k-1][p]?dp[k-1][p]:dp[k][p-1])+obstacleGrid[k][p];
			}
		}
		return dp[h - 1][l - 1];

	}
};

  




猜你喜欢

转载自www.cnblogs.com/wangshaowei/p/9294374.html