数字金字塔 c++简单递推求解

数字金字塔

题目:如下图出示了一个数字三角形,请编写一个程序计算从顶自底的某一条路径,使该路径经过的数字总和最大。(动态规划问题)

每一步可沿左斜线向下或右斜线向下
三角形行数(1~100,不一定是如图中的5行)
三角形中数字为整型

#include <iostream>
using namespace std;
int n;
int d[10][10];
int a[100][100];
void fun()
{
    
    
    int i,j;
    for (j=0; j<=n-1; j++) {
    
    
        d[n-1][j]=a[n-1][j];
    }
    for (i=n-2;i>=0; i--) {
    
    
        for (j=0; j<=i; j++) {
    
    
            d[i][j]=maxn(d[i+1][j], d[i+1][j+1])+a[i][j];
        }
    }
}
int maxn(int a,int b)
{
    
    
    return a>b?a:b;
}
int main(int argc, const char * argv[]) {
    
    
    cin>>n;
    int i,j;
    cout<<"please input the array"<<endl;
    for (i=0; i<n; i++) {
    
    
        for (j=0; j<=i; j++) {
    
    
            cin>>a[i][j];
        }
    }
    fun();
    cout<<d[0][0];
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46443659/article/details/109139130