Description
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
(Figure 1)
在上面的数字三角形中寻找一条从顶部到底边的路径,使得路径上所经过的数字之和最大。路径上的每一步都只能往左下或右下走。只需要求出这个最大和即可,不必给出具体路径。
Input
Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99.
Output
Your program is to write to standard output. The highest sum is written as an integer.
Sample Input
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
Sample Output
30
方法一:递推:
#include<iostream>
#include <cstdio>
#include <algorithm>
#include<cstring>
#define p 10001
using namespace std;
int main(){//递推
int N;
int a[100][100],b[101][100];
scanf("%d",&N);
for(int i=0;i<N;i++){
for(int j=0;j<=i;j++){
scanf("%d",&a[i][j]);
}
}
for(int j=0;j<N;j++){
b[N-1][j]=a[N-1][j];
}
for(int i=N-2;i>=0;i--){
for(int j=0;j<=i;j++){
b[i][j]=a[i][j]+max(b[i+1][j],b[i+1][j+1]);
}
}
printf("%d\n",b[0][0]);
}
方法二:递归动归:
(若单纯使用递归,会超时,因为有大量的重复运算)
#include<iostream>
#include <cstdio>
#include <algorithm>
#include<cstring>
#define p 10001
using namespace std;
int maxnum[101][101];
int N;
int a[100][100],b[101][100];
int Maxnum(int i,int j){
if(maxnum[i][j]!=-1)
return maxnum[i][j];
if(N==i)
return a[i][i];
else{
int s=Maxnum(i+1,j);
int t=Maxnum(i+1,j+1);
maxnum[i][j]=a[i][j]+max(s,t);
}
return maxnum[i][j];
}
int main(){
scanf("%d",&N);
for(int i=0;i<N;i++){
for(int j=0;j<=i;j++){
scanf("%d",&a[i][j]);
maxnum[i][j]=-1;
}
}
printf("%d\n",Maxnum(0,0));
}