Question
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.
Solution
-
动态规划。 p[i][j] = grid[i][j] + min(p[i - 1][j], p[i][j - 1]). 因为到达一个节点,最多有两种选择,当然是选择代价较小的。
-
时间复杂度O(n^2)。
Code
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
if (grid.size() <= 0)
return 0;
vector<vector<int>> tb(grid.size(), vector<int>(grid[0].size(), 0));
int row = grid.size();
int col = grid[0].size();
tb[0][0] = grid[0][0];
// 注意初始化是一个代价累加的过程
for (int i = 1; i < row; i++) {
tb[i][0] = grid[i][0] + tb[i - 1][0];
}
for (int i = 1; i < col; i++) {
tb[0][i] = grid[0][i] + tb[0][i - 1];
}
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
tb[i][j] = grid[i][j] + min(tb[i - 1][j], tb[i][j - 1]);
}
}
return tb[row - 1][col - 1];
}
};