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).
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.
本题本来的想法是用递归做,实现代码如下:
1 public class Solution {
2 public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
3 int row = triangle.size();
4 return findMinPath(triangle, 0, 0, row);
5 }
6
7 private int findMinPath(ArrayList<ArrayList<Integer>> triangle, int row,
8 int col, int totalRow) {
9 if (row == totalRow - 1) {
10 return triangle.get(row).get(col);
11 } else {
12 return triangle.get(row).get(col) + Math.min(findMinPath(triangle, row + 1, col, totalRow), findMinPath(triangle, row + 1, col + 1, totalRow));
13 }
14 }
15 }
提交之后发现超时,于是考虑到可能是递归的开销问题,考虑用迭代解题。实现如下:
1 public class Triangle {
2 public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
3 int n = triangle.size() - 1;
4 int[] path = new int[triangle.size()];
5 for (int o = 0; o < triangle.get(n).size(); o++) {
6 path[o] = triangle.get(n).get(o);
7 }
8 for (int i = triangle.size() - 2; i >= 0; i--) {
9 for (int j = 0, t = 0; j < triangle.get(i + 1).size() - 1; j++, t++) {
10 path[t] = triangle.get(i).get(t)
11 + Math.min(path[j], path[j + 1]);
12 }
13 }
14 return path[0];
15 }
16 }
这个解法的核心是从叶节点自底向上构造解空间。