您的位置:首页 > 其它

[LeetCode]120. Triangle

2016-12-18 19:02 316 查看
https://leetcode.com/problems/triangle/

找到三角中从上到下和最小

DP,从底往上,DP保存当前遍历行中当前位置到底部的最小和。

本题不应不会,显然DP。DP两种可能:从上到下 和 从下到上。又因本题必然要遍历所有元素。因此从下到上+依次遍历可得解。

public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int[] dp = new int[triangle.size() + 1];
for (int i = triangle.size() - 1; i >= 0; i--) {
for (int j = 0; j < triangle.get(i).size(); j++) {
dp[j] = triangle.get(i).get(j) + Math.min(dp[j], dp[j + 1]);
}
}
return dp[0];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: