Given an integer N, the task is to print all the possible ways in which N can be written as the sum of two or more positive integers.

Examples:

Input:_ N = 4_

Output:

1 1 1 1

1 1 2

1 3

2 2

Input:_ N = 3_

Output:

1 1 1

1 2

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: The idea is to use recursion to solve this problem. The idea is to consider every integer from 1 to N such that the sum N can be reduced by this number at each recursive call and if at any recursive call N reduces to zero then we will print the answer stored in the vector. Below are the steps for recursion:

  1. Get the number N whose sum has to be broken into two or more positive integers.
  2. Recursively iterate from value 1 to N as index i:
  • Base Case: If the value called recursively is 0, then print the current vector as this is the one of the way to broke N into two or more positive integers.
if (n == 0)
    printVector(arr);
  • Recursive Call: If the base case is not met, then Recursively iterate from [i, N – i]. Push the current element j into vector(say arr) and recursively iterate for the next index and after the this recursion ends then pop the element j inserted previously:
for j in range[i, N]:
    arr.push_back(j);
    recursive_function(arr, j + 1, N - j);
    arr.pop_back(j);   

#backtracking #greedy #arrays #algorithms

Print all possible ways to write N as sum of two
7.45 GEEK