Triangle LeetCode |My solution
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 class Solution { public int minimumTotal(List<List<Integer>> triangle) { if (triangle == null) { return 0; } int rowNumber = triangle.size() ; int [][] minArray = new int [rowNumber][rowNumber]; minArray[0][0] = triangle.get(0).get(0); for (int i = 1; i < rowNumber; i++) { for (int j = 0; j <= i ; j++) { if (j == 0) { minArray[i][j] = minArray[i-1][j] + triangle.get(i).get(j) ; } else if (j == i && j != 0) { minArray[i][j] = minArray[i-1][j - 1] + triangle.get(i).get(j); } else { minArray[i][j] = Math.min(minArray[i- 1][j] + triangle.get(i).get(j), minArray[i- 1][j - 1] + triangle.get(i).get(j)); } } } int min = minArray[rowNumber - 1][0]; for (int i = 0; i < rowNumber; i++) { if (min > minArray[rowNumber - 1][i]) { min = minArray[rowNumber - 1][i]; } } return min; } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步