2019.12.22 LeetCode 从零单刷个人笔记整理(持续更新)
github:https://github.com/ChopinXBP/LeetCode-Babel
自底向上的动态规划。建立dp数组,dp[j]代表当前层j位置的最小路径和,对于每一层i,自底向上有动态转移方程:
dp[j] = triangle.get(i - 1).get(j) + Math.min(dp[j], dp[j + 1]);
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。
例如,给定三角形:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
说明:
如果你可以只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题,那么你的算法会很加分。
import java.util.List;
/**
*
* Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
* 给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。
*
*/
public class Triangle {
public int minimumTotal(List<List<Integer>> triangle) {
int size = triangle.size();
int[] dp = new int[size];
for(int i = 0; i < size; i++){
dp[i] = triangle.get(size - 1).get(i);
}
for(int i = size - 1; i >= 0; i--) {
for(int j = 0; j < i; j++) {
dp[j] = triangle.get(i - 1).get(j) + Math.min(dp[j], dp[j + 1]);
}
}
return dp[0];
}
}
#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#