Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Construct a Special Triangle from a Given Array

Objec­tive: Given an array of inte­gers such that first level will print all the ele­ments in the array and from then at each level num­ber of ele­ments will be one less than the pre­vi­ous level and ele­ments at the level will be the Sum of con­sec­u­tive ele­ments in the pre­vi­ous level. Print it in a reverse level. See Example.

Exam­ple:

Construct-a-Special-Triangle-from-a-Given-Array

Construct-a-Special-Triangle-from-a-Given-Array

Approach:

  • Recur­sion is the key.
  • At each iter­a­tion cre­ate a new array which con­tains the Sum of con­sec­u­tive ele­ments in the array passes as parameter.
  • Make a recur­sive call and pass the newly cre­ated array in the pre­vi­ous step.
  • While back track­ing print the array (for print­ing in reverse order)

Code:


Out­put:

[48]
[20, 28]
[8, 12, 16]
[3, 5, 7, 9]
[1, 2, 3, 4, 5]

You may also like...