Digital triangle-recursion

Topic link: Portal (click me)

Ideas

Simple recursion to get the following formula

for(int i=1;i<=n;i++){
    
    
        for(int j=1;j<=i;j++){
    
    
               cin>>a[i][j];
               dp[i][j]=a[i][j]+max(dp[i-1][j-1],dp[i-1][j]);
        }
    }

The key to this question is the number of times the left and right of the lower deck of the lower deck must not differ by more than 1
Well, if the last position in this condition, only the inevitable path to meet in the middle of those two positions, they have gone x-step to the left, Go x steps to the right to return to the middle position

AC code

#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(false),cin.tie(0)
using namespace std;
#define MAXN  110
int dp[MAXN][MAXN],a[MAXN][MAXN],n;
//因为只能向左和向右,在数组里为向下和向右,如果要两者次数小于1,则路径最后一个位置必然在中间那两个位置上
int main()
{
    
    
    IOS;
    cin>>n;
    for(int i=1;i<=n;i++){
    
    
        for(int j=1;j<=i;j++){
    
    
               cin>>a[i][j];
               dp[i][j]=a[i][j]+max(dp[i-1][j-1],dp[i-1][j]);
        }
    }
   n%2==1?cout<<dp[n][(n+1)/2]:cout<<max(dp[n][n/2],dp[n][n/2+1]);
   return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43615816/article/details/115210606