数字三角形(动态规划)

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
#include 
#include 
#include
#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=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
#include 
#include 
#include
#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


 

你可能感兴趣的:(动态规划)