动态规划-120题triangle
2020-04-05 本文已影响0人
kason_zhang
动态规划:
将原问题拆解成若干子问题,同时保存子问题的答案,使得每个子问题只求解一次,最终获得原问题的答案。
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).
递归解法:
public int minimumTotal(List<List<Integer>> triangle) {
int min = Integer.MAX_VALUE;
if (triangle.size() == 1) {
return triangle.get(0).get(0);
}
for (int i = 0; i < triangle.size(); i++) {
int temp = minValue(triangle.size()-1, i, triangle);
if (min > temp){
min = temp;
}
}
return min;
}
/**
* 递归解法
* @param row
* @param col
* @param triangle
* @return
*/
public int minValue(int row, int col, List<List<Integer>> triangle) {
if (row == 0) {
return triangle.get(0).get(0);
}
if (col == 0) {
return minValue(row-1, 0, triangle) + triangle.get(row).get(col);
}
if (col == triangle.get(row).size() - 1) {
return minValue(row-1, triangle.get(row).size()-2, triangle)+ triangle.get(row).get(col);
}
return Math.min(minValue(row-1, col-1, triangle), minValue(row-1, col, triangle)) + triangle.get(row).get(col);
}
动态规划解法
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
// 存储走到第i行i列的最小值
int[][] minValues = new int[triangle.size() ][triangle.size()];
minValues[0][0] = triangle.get(0).get(0);
if (triangle.size() == 1) {
return minValues[0][0];
}
for (int row = 1; row < triangle.size(); row++) {
for (int col = 0; col <= row; col++) {
if (col == 0) {
minValues[row][col] = minValues[row-1][col] + triangle.get(row).get(col);
} else if (col == row) {
minValues[row][col] = minValues[row-1][col-1] + triangle.get(row).get(col);
} else {
minValues[row][col] = Math.min(minValues[row-1][col-1], minValues[row-1][col])+ triangle.get(row).get(col);
}
}
}
int min = Integer.MAX_VALUE;
for (int i = 0; i < triangle.size(); i++) {
min = Math.min(min,minValues[triangle.size()-1][i]);
}
return min;
}
}