[LintCode]最小パスと
3428 ワード
1 class Solution {
2 public:
3 /**
4 * @param grid: a list of lists of integers.
5 * @return: An integer, minimizes the sum of all numbers along its path
6 */
7 int minPathSum(vector<vector<int> > &grid) {
8 // write your code here
9 int m = grid.size();
10 int n = grid[0].size();
11 vector<int> cur(m, grid[0][0]);
12 for (int i = 1; i < m; i++)
13 cur[i] = cur[i - 1] + grid[i][0];
14 for (int j = 1; j < n; j++) {
15 cur[0] += grid[0][j];
16 for (int i = 1; i < m; i++)
17 cur[i] = min(cur[i - 1], cur[i]) + grid[i][j];
18 }
19 return cur[m - 1];
20 }
21 };