动态规划
解题思路:
- 用二维数组存放数字三角形:D( r, j) : 第r行第 j 个数字(r,j从1开始算)
- MaxSum(r, j) : 从D(r,j)到底边的各条路径中,最佳路径的数字之和
- 问题:求 MaxSum(1,1)
- D(r, j)出发,下一步只能走D(r+1,j)或者D(r+1, j+1)
参考:https://blog.csdn.net/u014492609/article/details/40510505
//动态规划,递推
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 101;
int arr[N][N];
int n;
int maxSum[N][N];
int main() {
int i, j;
cin >> n;
for (i = 1; i <= n; i++) {
for (j = 1; j <= i; j++)
cin >> arr[i][j];
}
for (i = 1; i <= n; i++)//初始化
maxSum[n][i] = arr[n][i];
for (i = n - 1; i >= 1; i--) {//递推
for (j = 1; j <= i; j++)
maxSum[i][j] = max(maxSum[i + 1][j], maxSum[i + 1][j + 1]) + arr[i][j];
}
cout << maxSum[1][1] << endl;
}