数字三角形
查看 提交 统计 提问
总时间限制: 1000ms 内存限制: 65536kB
描述
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
一个数字三角形。从三角形的顶部到底部有很多条不同的路径。对于每条路径,把路径上面的数加起来可以得到一个和,你的任务就是找到最大的和。
注意:路径上的每一步只能从一个数走到下一层上和它最近的左边的那个数或者右边的那个数。
输入:
输入的是一行是一个整数N (1 < N <= 100),给出三角形的行数。下面的N行给出数字三角形。数字三角形上的数的范围都在0和100之间。
输出:
输出最大的和。
样例输入
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
样例输出
30
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int n;
int a[100][100];
int res[100][100];
int Max(int r,int c){
if(res[r][c]!=-1){
return res[r][c];
}
else if(r==n){
res[r][c]= a[r][c];
}
else{
res[r][c]=max(Max(r+1,c+1)+a[r][c],Max(r+1,c)+a[r][c]);
}
return res[r][c];
}
int main(){
cin>>n;
//memset(res,-1,100*100*sizeof(int));
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
cin>>a[i][j];
res[i][j]=-1;
}
}
cout<<Max(1,1)<<endl;
return 0;
}
嗯,思路很简单,但单纯用递归的话会超时,
刚开始用的memset 一直报错。。。
后来注释掉换了个设初值的方法就过了
我也不是太明白为啥