64. Minimum Path Sum

2018/07/03 leetcode 共 764 字,约 3 分钟

title

problem link

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.

solution

DP,dp[i]表示在i列的路径和


class Solution {
public:
	int minPathSum(vector<vector<int>>& grid) {
		if (grid.size() == 0 || grid[0].size() == 0) {
			return 0;
		}
		int *dp = new int[grid[0].size()];
		fill(dp, dp + grid[0].size(), 0);
		for (int i = 0; i < grid.size(); i++) {
			for (int j = 0; j < grid[0].size(); j++) {
				if (i == 0) {
					dp[j] = dp[j - 1];
				}
				else if (j == 0) {
					dp[j] = dp[j];
				}
				else {
					dp[j] = min(dp[j], dp[j - 1]);
				}
				dp[j] += grid[i][j];
			}
		}
		return dp[grid[0].size() - 1];
	}
};

Search

    Table of Contents