最小路径和—动态规划

思路:定义一个网格大小的二维数组,先为第一行和第一列赋值。然后后面的值等于网格当前值加上二维数组上面和右面的最小的值。

 1 int minPathSum(vector<vector<int>> &grid) {
 2         // write your code here
 3         int row = grid.size();
 4         int col = grid[0].size();
 5         int ** sum = new int*[row];
 6         for (int i = 0; i < row; i++) {
 7             sum[i] = new int[col];
 8         }
 9         sum[0][0] = grid[0][0];
10         for (int i = 1; i < row; i++) {
11             sum[i][0] = sum[i-1][0] + grid[i][0];
12         }
13         for (int i = 0; i < col; i++) {
14             sum[0][i] = sum[0][i-1] + grid[0][i];
15         }
16         for (int i = 1; i < row; i++) {
17             for (int j= 1; j < col; j++) {
18                 int min_sum = min(sum[i-1][j], sum[i][j-1]);
19                 sum[i][j] = min_sum + grid[i][j];
20             }
21         }
22         return sum[row-1][col-1];
23     }

 

posted @ 2017-09-27 10:50  豆炸儿  阅读(496)  评论(0编辑  收藏  举报