[LeetCode]Triangle

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 triangleide

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

 

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

今天的最後一題Triangle是經典的動態規劃問題,第i行第j個節點接收來自第i-1行第j-1個節點和第j個節點的消息,計算出到達本身的最短路徑,再將消息向下層傳播。須要兩個數組,一個記錄上一行的路徑長度,一個計算當前行的路徑。code

代碼blog

 1 class Solution {
 2 public:
 3     const int INF=100000;
 4     int minimumTotal(vector<vector<int> > &triangle) {
 5         // Note: The Solution object is instantiated only once and is reused by each test case.
 6         int n = triangle.size();
 7         // 若triangle爲空,返回0
 8         if(n==0)
 9             return 0;
10         
11         vector<int> prev_sum = triangle[0];
12         vector<int> cur_sum;
13         for(int i=1; i<n; ++i)
14         {
15             int rnum = triangle[i].size(); // number of elements in a row
16             for(int j=0; j<rnum; ++j)
17             {
18                 int left = j>0?prev_sum[j-1]:INF; //最左側節點和最右側節點的處理
19                 int right = j<rnum-1?prev_sum[j]:INF;
20                 int cur = left<right?left:right;
21                 cur += triangle[i][j]; // 計算從根節點到此節點的最短路徑
22                 cur_sum.push_back(cur);
23             }
24             prev_sum = cur_sum;
25             cur_sum.clear();
26         }
27         // 在三角形底部找到最小路徑值
28         int minpath = prev_sum[0];
29         for(int i=1; i<n; ++i)
30             minpath = prev_sum[i]<minpath?prev_sum[i]:minpath;
31             
32         return minpath;
33     }
34 };
Triangle
本站公眾號
   歡迎關注本站公眾號,獲取更多信息