Find all combinations that add upto given number using C++


Suppose we have a positive number n. We have to find all combinations of positive numbers, that adds up to that number. Here we want only combinations, not the permutations. For the value n = 4, there will be [1, 1, 1, 1], [1, 1, 2], [2, 2], [1, 3], [4]

We will solve this using recursion. We have an array to store combinations, and we will fill that array using recursive approach. Each combination will be stored in increasing order of elements.

Example

#include<iostream>
using namespace std;
void getCombination(int arr[], int index, int num, int decrement) {
   if (decrement < 0)
      return;
   if (decrement == 0){
      for (int i = 0; i < index; i++)
         cout << arr[i] << " ";
         cout << endl;
         return;
   }
   int prev;
   if(index == 0)
   prev = 1;
   else
      prev = arr[index-1];
   for (int k = prev; k <= num ; k++) {
      arr[index] = k;
      getCombination(arr, index + 1, num, decrement - k);
   }
}
void findCombinations(int n) {
   int arr[n];
   getCombination(arr, 0, n, n);
}
int main() {
   int n = 4;
   findCombinations(n);
}

Output

1 1 1 1
1 1 2
1 3
2 2
4

Updated on: 01-Nov-2019

351 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements