思路一:搜索,但会超时,蓝桥杯填空题的话可参考
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int w[N][N];
int n;
int maxn = 0;
void dfs(int x,int y,int left,int right,int sum){
if(x==n){
if(abs(left-right)<=1&&sum>maxn){
maxn = sum;
}
return;
}
dfs(x+1,y,left+1,right,sum+w[x+1][y]);
dfs(x+1,y+1,left,right+1,sum+w[x+1][y+1]);
}
int main(){
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
scanf("%d",&w[i][j]);
}
}
dfs(1,1,0,0,w[1][1]);
cout<<maxn<<endl;
}
思路二:动态规划DP思路
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int w[N][N];
int f[N][N][N];
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
scanf("%d",&w[i][j]);
}
}
for(int i=1;i<=n;i++){
f[n][i][0] = w[n][i];
}
for(int i=n-1;i>=1;i--){
for(int j=1;j<=i;j++){
for(int k=0;k<=n-i;k++){
//从右下来
f[i][j][k] = f[i+1][j+1][k]+w[i][j];
if(k>=1){
f[i][j][k] = max(f[i+1][j][k-1]+w[i][j],f[i][j][k]);
}
}
}
}
//如果n为偶数,n-1为偶数,那么最多只能向左上走(n-1)/2次
if(n%2==1){
cout<<f[1][1][(n-1)/2]<<endl;
}else{//如果n为偶数,n-1为奇数,最多只只能向左上走n-1/2或者n-1/2+1次
cout<<max(f[1][1][(n-1)/2+1],f[1][1][(n-1)/2])<<endl;
}
}