Triangle minimum path sum
Title description: Given a triangle, find the minimum path sum from top to bottom.
Each step can only move to the adjacent node in the next row. Adjacent nodes here refer to two nodes whose subscript is the same as or equal to the subscript of the node of the previous layer + 1. In other words, if it is located at the subscript i of the current line, then the next step can be moved to the subscript i or i + 1 of the next line.
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/triangle/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution one: dynamic programming
Use an array to record the minimum path sum to the nodes of each layer, and then the dynamic programming process has the following basis:
- The first node of each layer can only be reached by the first node of the previous layer;
- The 2nd ~ size-1 nodes of each layer can be reached from the same position or the previous position of the previous layer, whichever is smaller;
- The last node of each layer can only be reached by the last node of the previous layer.
Finally, return to the minimum path sum to the last layer of nodes.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LeetCode_120 {
/**
* 动态规划
*
* @param triangle
* @return
*/
public static int minimumTotal(List<List<Integer>> triangle) {
// 记录到达每一层的每一个结点的路径和,初始化都是0
int[] result = new int[triangle.size()];
for (List<Integer> integers : triangle) {
// 记录到达当前层每一个结点的路径和,初始化都是0
int[] cur = new int[triangle.size()];
// 每一层的第一个结点只能由上一层的第一个结点到达
cur[0] = result[0] + integers.get(0);
int index;
for (index = 1; index < integers.size() - 1; index++) {
// 每一层的第 2 ~ size-1 个结点,可以有上一层相同位置或者上一个位置到达,取其中的较小值
cur[index] = integers.get(index) + Math.min(result[index - 1], result[index]);
}
if (index < integers.size()) {
// 每一层的最后一个结点只能由上一层的最后一个节点到达
cur[index] = integers.get(index) + result[index - 1];
}
result = cur;
}
// 最后,返回到达最后一层的最小的路径和的值
return Arrays.stream(result).min().getAsInt();
}
public static void main(String[] args) {
List<List<Integer>> triangle = new ArrayList<>();
List<Integer> one = new ArrayList<>();
one.add(2);
triangle.add(one);
List<Integer> two = new ArrayList<>();
two.add(3);
two.add(4);
triangle.add(two);
List<Integer> three = new ArrayList<>();
three.add(6);
three.add(5);
three.add(7);
triangle.add(three);
List<Integer> four = new ArrayList<>();
four.add(4);
four.add(1);
four.add(8);
four.add(3);
triangle.add(four);
System.out.println(minimumTotal(triangle));
}
}
[Daily Message] current hardship as an investment, an investment in the future, and you will have the freedom to be comfortable in the future.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。