Leetcode之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>>& grid) {
        int h = grid.size();
	if (h <= 0)return 0;
	int w = grid[0].size();
	if (w <= 0)return 0;
	vector<vector<int>> res(h, vector<int>(w, 0));

	for (int i = 0; i < h; i++) {
		for (int j = 0; j < w; j++) {
			if (i > 0 && j > 0) {
				int min = res[i - 1][j] < res[i][j - 1] ? res[i - 1][j] : res[i][j - 1];
				res[i][j] = min + grid[i][j];
			}
			else if (i == 0&&j>0) {
				res[i][j] = res[i][j - 1] + grid[i][j];
			}
			else if (j == 0&&i>0) {
				res[i][j] = res[i - 1][j] + grid[i][j];
			}
			else {
				res[i][j] = grid[i][j];
			}
		}
	}

	return res[h - 1][w - 1];
    }
};

思路:

动态规划法

猜你喜欢

转载自blog.csdn.net/qq_35455503/article/details/88928440