120. Triangle (三角形中最小路径之和)
https://leetcode.com/problems/triangle/?envType=study-plan-v2&envId=top-interview-150
题目解答:
https://leetcode.cn/problems/IlPe0q/solutions/1036365/san-jiao-xing-zhong-zui-xiao-lu-jing-zhi-srun/
详细题解:
https://blog.csdn.net/qq_41878358/article/details/105671159
class Solution { // public int minimumTotal(List<List<Integer>> triangle) { // //if(0<j<i) dp[i][j]=Math.min(dp[i-1][j-1], dp[i-1][j]) // //if(j==i) dp[i][i]=dp[i-1][j-1] // //if(j=0) dp[i][0]=dp[i-1][0] // // i=row num, j=column num // int[] res = new int[triangle.size() + 1]; // for (int i = triangle.size() - 1; i >= 0; i--) { // for (int j = 0; j < triangle.get(i).size(); j++) { // res[j] = Math.min(res[j], res[j + 1]) + triangle.get(i).get(j); // } // } // return res[0]; // } public int minimumTotal(List<List<Integer>> triangle) { if(triangle==null || triangle.size()==0){ return 0; } int rowSize = triangle.size(); // dp[i][j] 表示从最底部到 triangle[i][j] 的最小路径 int[][] dp= new int[rowSize][rowSize]; for(int i=0; i<triangle.get(rowSize-1).size(); i++){ dp[rowSize-1][i] = triangle.get(rowSize-1).get(i); } for(int i=rowSize-2; i>=0; i--){ for(int j=0; j<triangle.get(i).size(); j++){
// 递推公式 dp[i][j] = Math.min(dp[i+1][j], dp[i+1][j+1]) + triangle.get(i).get(j); } } return dp[0][0]; } }