Digital pyramid maximum path and--recursion

Source: Internet
Author: User

The topic description assumes that there is a digital pyramid as shown below, and now requires writing a program to find the path that ends at any point from the vertex to the bottom, making the path pass through the number and maximum, and outputting the maximum and the path. For example, the following pyramid and maximum path are 7+3+8+7+5=30.
73 28 1 02 7 4 44 5 2 6 5 C + + Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21st
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<iostream>
#include<cmath>

using namespacestd;

Const intMaxlayer =5; //maximum number of layers for pyramids

/** @brief
* Calculates the subscript in the array for the POS element of the layer in the pyramid
*
* @param layer int Pyramid
* @param pos int pyramid element of the first layer
* @return int
*
*/
intIndex (intlayer,intPOS)
{
returnLayer * (Layer-1) / 2+ pos;
}

/** @brief
* Pyramid top-down path, path and maximum value
*
* @param pnums int* stores the numbers in the pyramid, here is a one-dimensional array, stored in a hierarchical order
* @param layer int pyramid [1, Maxlayer]
* @param POS ([0, layer-1]) elements of the first layer of the section layer in the point of sale int pyramid
* @return int maximum path and
*
*/
intMaxpathsum (int*pnums,intlayer,intPOS)
{
if(Maxlayer = = layer)
{
returnpnums[index (layer, POS)];
}

/**
* The first POS element of layer layers, can only go to the first Pos or pos+1 element of the layer+1 layer
*/
returnMax (maxpathsum (pnums, layer +1, POS +0), maxpathsum (pnums, layer +1, POS +1))
+ pnums[index (layer, POS)];
}

intMain ()
{
//The size of the array should be Maxlayer * (Maxlayer + 1)/2
    intnums[] = {7, 3, 2, 8, 1, 0, 2, 7, 4, 4, 4, 5, 2 ,6, 5};
cout << maxpathsum (nums,1, 0) << Endl;

return 0;
}
Note: The program test is limited, the lack of hope to point out. Please do not hesitate to enlighten!

Digital pyramid maximum path and--recursion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.