Description:
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).
Solution:
前面做过类似的题目,用DP解决。可以从下到上,也可以从上到下。这里用了从下到上,因为这样,dp[0][0]就是最终的结果;否则从上到下,需要最后一层进行一次遍历。
dp[i][j]表示从最后一层到这个点,最短的和。状态转移方程:
dp[i][j] = dp[i][j] + min( dp[i+1][j], dp[i+1][j+1] );
import java.util.*;
public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int n = triangle.size();
int dp[][] = new int[n][n];
Iterator<List<Integer>> lineIterator = triangle.iterator();
for (int i = 0; i < n; i++) {
ArrayList<Integer> line = (ArrayList<Integer>) lineIterator.next();
Iterator<Integer> ite = line.iterator();
for (int j = 0; j <= i; j++) {
dp[i][j] = ite.next();
}
}
for (int i = n - 2; i >= 0; i--) {
for (int j = 0; j <= i; j++)
dp[i][j] += Math.min(dp[i + 1][j], dp[i + 1][j + 1]);
}
return dp[0][0];
}
}