递归写法 从上往下
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<math.h>
#include<algorithm>
#include<map>
#include<cstring>
#include<set>
using namespace std;
const int maxn = 1100;
int f[maxn][maxn], dp[maxn][maxn];
int n;
int getans(int i, int j)
{
if (dp[i][j] != 0)
return dp[i][j];
if (i == n)
return f[i][j];
dp[i][j] = max(getans(i+1,j), getans(i+1,j+1)) + f[i][j];
return dp[i][j];
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
cin >> f[i][j];
}
}
cout << getans(1, 1);
}
递推写法 从下往上
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<math.h>
#include<algorithm>
#include<map>
#include<cstring>
#include<set>
using namespace std;
const int maxn = 1100;
int f[maxn][maxn], dp[maxn][maxn];
int n;
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
cin >> f[i][j];
}
}
for (int j = 1; j <= n; j++)
{
dp[n][j] = f[n][j];
}
for (int i = n - 1; i >= 1; i--)
{
for (int j = 1; j <= i; j++)
{
dp[i][j] = max(dp[i + 1][j], dp[i + 1][j + 1]) + f[i][j];
}
}
cout << dp[i][j] << endl;
return 0;
}