【LeetCode】#120三角形最小路径和(Triangle)
题目描述
给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。
示例
例如,给定三角形:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
Description
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
Example
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).
解法
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
if (triangle == null || triangle.size() == 0){
return 0;
}
int[][] dp = new int[triangle.size()+1][triangle.size()+1];
for (int i = triangle.size()-1; i>=0; i--){
List<Integer> curTr = triangle.get(i);
for(int j = 0 ; j< curTr.size(); j++){
dp[i][j] = Math.min(dp[i+1][j], dp[i+1][j+1]) + curTr.get(j);
}
}
return dp[0][0];
}
}