Minimum Path Sum
Description
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.
Notice You can only move either down or right at any point in time.
Example
Link
Method
- Dp, record min sum, considering the boundary
- x
Example
- 1
class Solution { public: /** * @param grid: a list of lists of integers. * @return: An integer, minimizes the sum of all numbers along its path */ int minPathSum(vector<vector<int> > &grid) { // write your code here if (grid.empty()) { return 0; } int m = grid.size(); int n = grid[0].size(); vector<vector<int>>& dp = grid; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (i == 0 && j == 0) { continue; } else if (i == 0 && j != 0) { dp[i][j] += dp[i][j-1]; } else if (i != 0 && j == 0) { dp[i][j] += dp[i-1][j]; } else { dp[i][j] += min(dp[i-1][j], dp[i][j-1]); } } } return dp[m-1][n-1]; } };
Similar problems
x
Tags
x