题目链接
题目:
dp入门题,因为数据的原因好像也可以暴力搜索过这个题,但是我是来学dp的。。。。。。博主初学。。。。。详情代码
思路:
从这个数字三角形的下方开始寻找最优子结构。
AC代码
#include <bits/stdc++.h>
inline int read(){char c = getchar();int x = 0,s = 1;
while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}
while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}
return x*s;}
using namespace std;
#define NewNode (TreeNode *)malloc(sizeof(TreeNode))
#define Mem(a,b) memset(a,b,sizeof(a))
const int N = 1e8 + 5;
const long long INFINF = 0x7f7f7f7f7f7f7f;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-7;
const unsigned long long mod = 998244353;
const double II = acos(-1);
const double PP = (II*1.0)/(180.00);
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> piil;
int dp[1010][1010],arr[1010][1010];
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int n;
cin >> n;
for(int i = 1;i <= n;i++)
for(int j = 1;j <= i;j++)
{cin >> arr[i][j];dp[i][j] = arr[i][j];}先让dp数组初始化
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]) + arr[i][j];//每次这个数能走到其右下方或者正下方。
cout << dp[1][1] << endl;
}