|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| -import java.util.ArrayList; |
4 |
| -import java.util.Arrays; |
5 | 3 | import java.util.List;
|
6 | 4 |
|
7 |
| -/**Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. |
| 5 | +/** |
| 6 | + * 120. Triangle |
| 7 | +
|
| 8 | + Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. |
8 | 9 |
|
9 | 10 | For example, given the following triangle
|
10 | 11 | [
|
|
17 | 18 |
|
18 | 19 | Note:
|
19 | 20 | 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.*/
|
20 |
| -public class _120 { |
21 | 21 |
|
22 |
| - public static int minimumTotal(List<List<Integer>> triangle) { |
23 |
| - /**https://discuss.leetcode.com/topic/1669/dp-solution-for-triangle, @stellari has a very excellent explanation. |
24 |
| - * Basically, we use the bottom-up approach, starting from the bottom row of this triangle, and we only need to store the shortest path of each node |
25 |
| - * from its last row, and keep overwriting it until we reach the top.*/ |
26 |
| - int n = triangle.size(); |
27 |
| - List<Integer> cache = triangle.get(n - 1); |
28 |
| - |
29 |
| - for (int layer = n - 2; layer >= 0; layer--) { |
30 |
| - //for each layer |
31 |
| - for (int i = 0; i <= layer; i++) { |
32 |
| - //check its very node |
33 |
| - int value = Math.min(cache.get(i), cache.get(i + 1)) + triangle.get(layer).get(i); |
34 |
| - cache.set(i, value); |
35 |
| - } |
| 22 | +public class _120 { |
| 23 | + public static class Solution1 { |
| 24 | + public int minimumTotal(List<List<Integer>> triangle) { |
| 25 | + int n = triangle.size(); |
| 26 | + List<Integer> cache = triangle.get(n - 1); |
| 27 | + |
| 28 | + for (int layer = n - 2; layer >= 0; layer--) { |
| 29 | + //for each layer |
| 30 | + for (int i = 0; i <= layer; i++) { |
| 31 | + //check its very node |
| 32 | + int value = Math.min(cache.get(i), cache.get(i + 1)) + triangle.get(layer).get(i); |
| 33 | + cache.set(i, value); |
36 | 34 | }
|
37 |
| - return cache.get(0); |
| 35 | + } |
| 36 | + return cache.get(0); |
38 | 37 | }
|
39 |
| - |
40 |
| - public static void main(String... strings) { |
41 |
| - List<List<Integer>> triangle = new ArrayList(); |
42 |
| - triangle.add(Arrays.asList(1)); |
43 |
| - triangle.add(Arrays.asList(2, 3)); |
44 |
| - System.out.println(minimumTotal(triangle)); |
45 |
| - } |
46 |
| - |
| 38 | + } |
47 | 39 | }
|
0 commit comments