Topic:
,
3
2 3
4 3 4 4
7 numbers form a three-layer digital triangle, and the affiliation is a tree-shaped relationship. Requires a number to be selected in each layer according to the affiliation, so that the final and maximum.
Analysis:
If you choose from the bottom down, the more you choose, the more complex the problem is. Considering the selection from bottom to top, the dynamic programming method is used to consider the local. The largest part is the largest of the whole. I wrote it in C + +.
Code:
1#include <iostream>2 using namespacestd;3 intMain ()4 {5 inttriangle[ -][ -];6 inti;7 intJ;8 intN;9cout<<"Please enter the number of layers of the triangle:";TenCin>>N; One while(n!=0) A { -cout<<"enter the values for each layer of triangles, in turn:"<<Endl; - for(i=1; i<=n;i++) the { - for(j=1; j<=i;j++) - { -Cin>>Triangle[i][j]; + } - } + A for(i=n-1;i>0; i--) at { - for(j=i;j>0; j--) - { -triangle[i][j]+=triangle[i+1][j+1]>triangle[i+1][j]?triangle[i+1][j+1]:triangle[i+1][j]; - } - } incout<<"The maximum values for each layer of the number triangle are:"<<triangle[1][1]<<Endl; - Break; to } + return 0; -}View Code
Figure Triangle Solution