Last active
February 21, 2023 18:20
-
-
Save daifu/4645262 to your computer and use it in GitHub Desktop.
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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). | |
| Note: | |
| Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. | |
| */ | |
| public class Solution { | |
| public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) { | |
| // Start typing your Java solution below | |
| // DO NOT write main() function | |
| if (triangle.size() == 0) return 0; | |
| int size = triangle.size(); | |
| int min = Integer.MAX_VALUE; | |
| int[] sum = new int[size];; | |
| sum[0] = triangle.get(0).get(0); | |
| for(int cur = 1; cur <= size - 1; cur++){ | |
| int next_size = triangle.get(cur).size(); | |
| // it has to start with the end of the array | |
| // because the further one need the clean sum | |
| // value than the newer one. | |
| for(int next = next_size - 1; next >= 0; next--) { | |
| if (next == 0) { | |
| sum[0] = sum[0] + triangle.get(cur).get(next); | |
| } else if (next == (next_size - 1)) { | |
| sum[next] = sum[next-1] + triangle.get(cur).get(next); | |
| } else { | |
| sum[next] = Math.min(sum[next-1], sum[next]) + triangle.get(cur).get(next); | |
| } | |
| } | |
| } | |
| for(int i = 0; i < size; i++){ | |
| if(sum[i] < min){ | |
| min = sum[i]; | |
| } | |
| } | |
| return min; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
public static int minimumTotal(List<List> triangle) {