Find all combinations that add upto given number

31 Mar, 2021
Given a positive number, find out all combinations of positive numbers that adds upto that number. The program should print only combinations, not permutations. For example, for input 3, either 1, 2 or 2, 1 should be printed.Examples : 
Input: N = 3
Output:
1 1 1
1 2
3

Input: N = 5
Output:
1 1 1 1 1
1 1 1 2
1 1 3
1 2 2
1 4
2 3
5 
We strongly recommend you to minimize your browser and try this yourself first.The idea is to use recursion. We use an array to store combinations and we recursively fill the array and recurse with reduced number. The invariant used in the solution is that each combination will always be stored in increasing order of elements involved. That way we can avoid printing permutations.Below is implementation of above idea :  
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find out all combinations of// positive numbers that add upto given number#include <iostream>using namespace std; /*    arr - array to store the combination    index - next location in array    num - given number    reducedNum - reduced number */void findCombinationsUtil(int arr[], int index,                       int num, int reducedNum){    // Base condition    if (reducedNum < 0)        return;     // If combination is found, print it    if (reducedNum == 0)    {        for (int i = 0; i < index; i++)            cout << arr[i] << " ";        cout << endl;        return;    }     // Find the previous number stored in arr[]    // It helps in maintaining increasing order    int prev = (index == 0)? 1 : arr[index-1];     // note loop starts from previous number    // i.e. at array location index - 1    for (int k = prev; k <= num ; k++)    {        // next element of array is k        arr[index] = k;         // call recursively with reduced number        findCombinationsUtil(arr, index + 1, num,                                 reducedNum - k);    }} /* Function to find out all combinations of   positive numbers that add upto given number.   It uses findCombinationsUtil() */void findCombinations(int n){    // array to store the combinations    // It can contain max n elements    int arr[n];     //find all combinations    findCombinationsUtil(arr, 0, n, n);} // Driver codeint main(){    int n = 5;    findCombinations(n);    return 0;}
// Java program to find out// all combinations of positive// numbers that add upto given// numberimport java.io.*; class GFG{    /* arr - array to store the    combination    index - next location in array    num - given number    reducedNum - reduced number */static void findCombinationsUtil(int arr[], int index,                                 int num, int reducedNum){    // Base condition    if (reducedNum < 0)        return;     // If combination is    // found, print it    if (reducedNum == 0)    {        for (int i = 0; i < index; i++)                System.out.print (arr[i] + " ");            System.out.println();        return;    }     // Find the previous number    // stored in arr[]. It helps    // in maintaining increasing    // order    int prev = (index == 0) ?                          1 : arr[index - 1];     // note loop starts from    // previous number i.e. at    // array location index - 1    for (int k = prev; k <= num ; k++)    {        // next element of        // array is k        arr[index] = k;         // call recursively with        // reduced number        findCombinationsUtil(arr, index + 1, num,                                 reducedNum - k);    }} /* Function to find out allcombinations of positivenumbers that add upto givennumber. It uses findCombinationsUtil() */static void findCombinations(int n){    // array to store the combinations    // It can contain max n elements    int arr[] = new int [n];     // find all combinations    findCombinationsUtil(arr, 0, n, n);} // Driver codepublic static void main (String[] args){    int n = 5;    findCombinations(n);}} // This code is contributed// by akt_mit
# Python3 program to find out all# combinations of positive# numbers that add upto given number # arr - array to store the combination# index - next location in array# num - given number# reducedNum - reduced numberdef findCombinationsUtil(arr, index, num,                              reducedNum):     # Base condition    if (reducedNum < 0):        return     # If combination is    # found, print it    if (reducedNum == 0):         for i in range(index):            print(arr[i], end = " ")        print("")        return     # Find the previous number stored in arr[].    # It helps in maintaining increasing order    prev = 1 if(index == 0) else arr[index - 1]     # note loop starts from previous    # number i.e. at array location    # index - 1    for k in range(prev, num + 1):                 # next element of array is k        arr[index] = k         # call recursively with        # reduced number        findCombinationsUtil(arr, index + 1, num,                                 reducedNum - k) # Function to find out all# combinations of positive numbers# that add upto given number.# It uses findCombinationsUtil()def findCombinations(n):         # array to store the combinations    # It can contain max n elements    arr = [0] * n     # find all combinations    findCombinationsUtil(arr, 0, n, n) # Driver coden = 5;findCombinations(n); # This code is contributed by mits
// C# program to find out all// combinations of positive numbers// that add upto given numberusing System; class GFG{ /* arr - array to store thecombinationindex - next location in arraynum - given numberreducedNum - reduced number */static void findCombinationsUtil(int []arr, int index,                                 int num, int reducedNum){    // Base condition    if (reducedNum < 0)        return;     // If combination is    // found, print it    if (reducedNum == 0)    {        for (int i = 0; i < index; i++)            Console.Write (arr[i] + " ");            Console.WriteLine();        return;    }     // Find the previous number    // stored in arr[]. It helps    // in maintaining increasing    // order    int prev = (index == 0) ?                          1 : arr[index - 1];     // note loop starts from    // previous number i.e. at    // array location index - 1    for (int k = prev; k <= num ; k++)    {        // next element of        // array is k        arr[index] = k;         // call recursively with        // reduced number        findCombinationsUtil(arr, index + 1, num,                                 reducedNum - k);    }} /* Function to find out allcombinations of positivenumbers that add upto givennumber. It uses findCombinationsUtil() */static void findCombinations(int n){    // array to store the combinations    // It can contain max n elements    int []arr = new int [n];     // find all combinations    findCombinationsUtil(arr, 0, n, n);} // Driver codestatic public void Main (){    int n = 5;    findCombinations(n);}} // This code is contributed// by akt_mit
<?php// PHP program to find out all// combinations of positive// numbers that add upto given number /* arr - array to store the combination    index - next location in array    num - given number    reducedNum - reduced number */function findCombinationsUtil($arr, $index,                              $num, $reducedNum){    // Base condition    if ($reducedNum < 0)        return;     // If combination is    // found, print it    if ($reducedNum == 0)    {        for ($i = 0; $i < $index; $i++)            echo $arr[$i] , " ";        echo "\n";        return;    }     // Find the previous number    // stored in arr[] It helps    // in maintaining increasing order    $prev = ($index == 0) ? 1 : $arr[$index - 1];     // note loop starts from previous    // number i.e. at array location    // index - 1    for ($k = $prev; $k <= $num ; $k++)    {        // next element of array is k        $arr[$index] = $k;         // call recursively with        // reduced number        findCombinationsUtil($arr, $index + 1,                             $num, $reducedNum - $k);    }} /* Function to find out allcombinations of positive numbersthat add upto given number.It uses findCombinationsUtil() */function findCombinations($n){    // array to store the combinations    // It can contain max n elements    $arr = array();     //find all combinations    findCombinationsUtil($arr, 0, $n, $n);} // Driver code$n = 5;findCombinations($n); // This code is contributed by ajit?>
<script> // Javascript program to find out// all combinations of positive// numbers that add upto given// number     /* arr - array to store the    combination    index - next location in array    num - given number    reducedNum - reduced number */function findCombinationsUtil(arr, index,                                 num, reducedNum){    // Base condition    if (reducedNum < 0)        return;      // If combination is    // found, print it    if (reducedNum == 0)    {        for (let i = 0; i < index; i++)               document.write (arr[i] + " ");           document.write("<br/>");        return;    }      // Find the previous number    // stored in arr[]. It helps    // in maintaining increasing    // order    let prev = (index == 0) ?                          1 : arr[index - 1];      // note loop starts from    // previous number i.e. at    // array location index - 1    for (let k = prev; k <= num ; k++)    {        // next element of        // array is k        arr[index] = k;          // call recursively with        // reduced number        findCombinationsUtil(arr, index + 1, num,                                 reducedNum - k);    }}  /* Function to find out allcombinations of positivenumbers that add upto givennumber. It uses findCombinationsUtil() */function findCombinations(n){    // array to store the combinations    // It can contain max n elements    let arr = [];      // find all combinations    findCombinationsUtil(arr, 0, n, n);} // Driver Code     let n = 5;    findCombinations(n);                             </script>
Output : 
1 1 1 1 1 
1 1 1 2 
1 1 3 
1 2 2 
1 4 
2 3 
5 
Exercise : Modify above solution to consider only distinct elements in a combination.This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
jit_t
Mithun Kumar
sksyp
souravghosh0416
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Minimum number of jumps to reach end
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Find minimum number of coins that make a given value
Modulo 10^9+7 (1000000007)
Modulo Operator (%) in C/C++ with Examples
Program for factorial of a number