120. Triangle
by Botao Xiao
Question
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).
Thinking:
- Method 1:dp:二维数组
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
if(triangle == null || triangle.size() == 0) return 0;
int len = triangle.size();
int[][] dp = new int[len][len];
dp[0][0] = triangle.get(0).get(0);
for(int i = 1; i < len; i++){
dp[i][0] = dp[i - 1][0] + triangle.get(i).get(0);
dp[i][i] = dp[i - 1][i - 1] + triangle.get(i).get(i);
}
for(int i = 2; i < len; i++){
for(int j = 1; j < i; j++){
dp[i][j] = Math.min(dp[i - 1][j - 1], dp[i - 1][j]) + triangle.get(i).get(j);
}
}
int result = dp[len - 1][0];
for(int i = 1; i < len; i++){
result = Math.min(result, dp[len - 1][i]);
}
return result;
}
}
- Method 2: DP,一维,倒三角,从下往上,dp存储当前行的每一个位置的最短路径。
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int len = triangle.size();
int[] dp = new int[len + 1];
for(int i = len - 1; i >= 0; i--){
List<Integer> temp = triangle.get(i);
for(int j = 0; j < temp.size(); j++){
dp[j] = Math.min(dp[j], dp[j + 1]) + temp.get(j);
}
}
return dp[0];
}
}
二刷
和一刷的思路一样。使用一维数组dp.
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int size = triangle.size();
int[] dp = new int[size + 1];
for(int i = size - 1; i >= 0; i--){
List<Integer> temp = triangle.get(i);
int sz = temp.size();
for(int j = 0 ; j < sz; j++)
dp[j] = Math.min(dp[j], dp[j + 1]) + temp.get(j);
}
return dp[0];
}
}
Subscribe via RSS