题目
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
这题最适合的从下到上直接求解,直接根据下一行计算当前行的最小值即可。由题目可知,不希望你更改原有的数据,额外开辟的O(n)数组纪录就是了。见解法2
这题没写入参是否为null的判断了- - !
解法1
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Triangle {
private ArrayList
> triangle;
private int N;
private Map
records; public int minimumTotal(ArrayList
> triangle) { this.records = new HashMap
(); this.triangle = triangle; this.N = triangle.size(); return solve(0, 0); } private int solve(int level, int index) { int key = level * N + index; if (records.containsKey(key)) { return records.get(key); } int value = triangle.get(level).get(index); if (level == N - 1) { records.put(key, value); return value; } value += Math.min(solve(level + 1, index), solve(level + 1, index + 1)); records.put(key, value); return value; } }
解法2
public class Triangle {
public int minimumTotal(ArrayList
> triangle) {
int N = triangle.size();
Integer[] result = (Integer[]) triangle.get(N - 1).toArray(
new Integer[N]);
ArrayList
currentRow = null; for (int i = N - 2; i >= 0; --i) { currentRow = triangle.get(i); for (int j = 0; j < i + 1; ++j) { result[j] = Math.min(result[j], result[j + 1]) + currentRow.get(j); } } return result[0]; } }