Be the first user to complete this post

  • 0
Add to List
Beginner

124. Construct a Special Triangle from a Given Array

Objective: Given an array of integers such that first level will print all the elements in the array and from then at each level number of elements will be one less than the previous level and elements at the level will be the Sum of consecutive elements in the previous level. Print it in a reverse level. See Example.

Example:

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

Approach:

  • Recursion is the key.
  • At each iteration create a new array that contains the Sum of consecutive elements in the array passes as a parameter.
  • Make a recursive call and pass the newly created array in the previous step.
  • While backtracking print the array (for printing in reverse order)

Code:


Output:

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