題目:
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
[ [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).
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.
題解:
一道動態規劃的經典題目。需要自底向上求解。
遞推公式是: dp[i][j] = dp[i+1][j] + dp[i+1][j+1] ,當前這個點的最小值,由他下面那一行臨近的2個點的最小值與當前點的值相加得到。
由於是三角形,且歷史資料只在計算最小值時應用一次,所以無需建立二維陣列,每次更新1維陣列值,最後那個值裡存的就是最終結果。
程式碼如下:
1 public int minimumTotal(List<List<Integer>> triangle) {
2 if(triangle.size()==1)
3 return triangle.get(0).get(0);
4
5 int[] dp = new int[triangle.size()];
6
7 //initial by last row
8 for (int i = 0; i < triangle.get(triangle.size() - 1).size(); i++) {
9 dp[i] = triangle.get(triangle.size() - 1).get(i);
10 }
11
12 // iterate from last second row
13 for (int i = triangle.size() - 2; i >= 0; i--) {
14 for (int j = 0; j < triangle.get(i).size(); j++) {
15 dp[j] = Math.min(dp[j], dp[j + 1]) + triangle.get(i).get(j);
16 }
17 }
18
19 return dp[0];
20 }
2 if(triangle.size()==1)
3 return triangle.get(0).get(0);
4
5 int[] dp = new int[triangle.size()];
6
7 //initial by last row
8 for (int i = 0; i < triangle.get(triangle.size() - 1).size(); i++) {
9 dp[i] = triangle.get(triangle.size() - 1).get(i);
10 }
11
12 // iterate from last second row
13 for (int i = triangle.size() - 2; i >= 0; i--) {
14 for (int j = 0; j < triangle.get(i).size(); j++) {
15 dp[j] = Math.min(dp[j], dp[j + 1]) + triangle.get(i).get(j);
16 }
17 }
18
19 return dp[0];
20 }
Reference: http://www.programcreek.com/2013/01/leetcode-triangle-java/