题目链接

  题目要求: 

  Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

  For example, given the following triangle

1 [
2      [2],
3     [3,4],
4    [6,5,7],
5   [4,1,8,3]
6 ]

  The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

  Note:
  Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

  具体代码如下:

 1 class Solution {
 2 public:
 3     int minimumTotal(vector<vector<int> > &triangle) {
 4         int rows = triangle.size();
 5         if(rows == 0)
 6             return 0;
 7         
 8         int * dp = new int[rows];
 9         int szOfLastRow = triangle[rows - 1].size();
10         for(int i = 0; i < szOfLastRow; i++)
11             dp[i] = triangle[rows - 1][i];
12         
13         for(int i = rows - 2; i > -1; i--)
14         {
15             int cols = triangle[i].size();
16             for(int j = 0; j < cols; j++)
17                 dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]);
18         }
19         
20         return dp[0];
21     }
22 };
View Code

相关文章:

  • 2021-10-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-02-07
  • 2021-07-21
  • 2022-12-23
  • 2021-07-25
  • 2021-04-09
相关资源
相似解决方案