您的位置:首页 > 其它

120. Triangle

2017-01-17 13:24 253 查看
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).

public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
if(triangle.size() == 0 || triangle == null){
return -1;
}
if(triangle.get(0).size() == 0 || triangle.get(0) == null){
return -1;
}
int n = triangle.size();
int[][] dp = new int

;

for(int i = 0; i < n; i++){
dp[n - 1][i] = triangle.get(n-1).get(i);
}

for(int i = n - 2; i > 0 ; i--){
for(int j = 0; j < i; j++){
dp[i][j] = Math.min(dp[i + 1][j], dp[i + 1][j + 1]) + triangle.get(i).get(j);
}
}

return dp[0][0];
}

自底向上,dp[i][j]代表从i,j点到底部最小的和
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: