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 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问题,状态可以定义成dp[node]表示从当前node到bottom的最小路径和,对于最下面一层,因为它们是最底层,故它们到bottom的最小路径和就是它们自身;再往上一层,如节点6,它到达bottom的最小路径和即为节点4与节点1之间的最小值加上节点6自身的值
由以上分析得出状态迁移方程:
dp[node] = value[node] + min(dp[child1], dp[child2])
另外本题要求时间复杂度为:O(n), n为三角形的行数
1 public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 if(triangle == null || triangle.size() == 0){ 5 return 0; 6 } 7 8 int row = triangle.size(); 9 int[] num = new int[row]; 10 for(int i = row - 1; i >= 0; i--){ 11 int col = triangle.get(i).size(); 12 for(int j = 0; j < col; j++){ 13 if(i == row - 1){ 14 num[j] = triangle.get(i).get(j); 15 continue; 16 } 17 num[j] = Math.min(num[j], num[j+1]) + triangle.get(i).get(j); 18 } 19 } 20 return num[0]; 21 }