王争老师动态规划讲得确实精彩,就是课后练习没有答案,有时候解不出来会很难受。我是看了下一篇文章的讲解然后明白了这篇文章的课后习题解法,这里分享一下吧,希望对大家有帮助。
int[][] matrix = {{5},{7,8},{2,3,4},{4,9,6,1},{2,7,9,4,5}};
public int yanghuiTriangle(int[][] matrix) {
int[][] state = new int[matrix.length][matrix.length];
state[0][0] = matrix[0][0];
for (int i = 1; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (j == 0) state[i][j] = state[i - 1][j] + matrix[i][j];
else if (j == matrix[i].length - 1) state[i][j] = state[i - 1][j - 1] + matrix[i][j];
else {
int top1 = state[i - 1][j - 1];
int top2 = state[i - 1][j];
state[i][j] = Math.min(top1, top2) + matrix[i][j];
}
}
}
int minDis = Integer.MAX_VALUE;
for (int i = 0; i < matrix[matrix.length - 1].length; i++) {
int distance = state[matrix.length - 1][i];
if (distance < minDis) minDis = distance;
}
return minDis;
}
展开