Print combinations of distinct numbers which add up to give sum N

Given a positive integer N, the task is to find out all the combinations of positive integers that add upto the given integer N. The program should print only combinations, not permutations and all the integers in a combination must be distinct. For example, for input 3, either 1, 2 or 2, 1 should be printed and 1, 1, 1 must not be printed as the integers are not distinct.

Examples:

Input: N = 3
Output:
1 2
3



Input: N = 7
Output:
1 2 4
1 6
2 5
3 4
7

Approach: The approach is an extension of the approach discussed here. The idea used to get all the distinct element is that first we find all the elements that add up to give sum N. Then we iterate over each of the elements and store the elements into the set. Storing the elements into set would remove all the duplicate elements, and after that we add up the sum of the elements of the set and check whether it is equal to N or not.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
/* arr[] to store all the distinct elements
    index - next location in array 
    num - given number 
    reducedNum - reduced number */
void findCombinationsUtil(int arr[], int index,
                          int n, int red_num)
{
  
    // Set to store all the
    // distinct elements
    set<int> s;
    int sum = 0;
  
    // Base condition
    if (red_num < 0) {
        return;
    }
  
    if (red_num == 0) {
  
        // Iterate over all the elements
        // and store it into the set
        for (int i = 0; i < index; i++) {
            s.insert(arr[i]);
        }
  
        // Calculate the sum of all
        // the elements of the set
        for (auto itr = s.begin();
             itr != s.end(); itr++) {
            sum = sum + (*itr);
        }
  
        // Compare whether the sum is equal to n or not,
        // if it is equal to n print the numbers
        if (sum == n) {
            for (auto i = s.begin();
                 i != s.end(); i++) {
                cout << *i << " ";
            }
            cout << endl;
            return;
        }
    }
  
    // Find previous number stored in the array
    int prev = (index == 0) ? 1 : arr[index - 1];
  
    for (int k = prev; k <= n; k++) {
  
        // Store all the numbers recursively
        // into the arr[]
        arr[index] = k;
        findCombinationsUtil(arr, index + 1,
                             n, red_num - k);
    }
}
  
// Function to find all the
// distinct combinations of n
void findCombinations(int n)
{
    int a[n];
    findCombinationsUtil(a, 0, n, n);
}
  
// Driver code
int main()
{
    int n = 7;
    findCombinations(n);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.*;
class GFG 
{
  
/* arr[] to store all the distinct elements
    index - next location in array 
    num - given number 
    reducedNum - reduced number */
static void findCombinationsUtil(int arr[], int index,
                        int n, int red_num)
{
  
    // Set to store all the
    // distinct elements
    HashSet<Integer> s = new HashSet<>();
    int sum = 0;
  
    // Base condition
    if (red_num < 0
    {
        return;
    }
  
    if (red_num == 0
    {
  
        // Iterate over all the elements
        // and store it into the set
        for (int i = 0; i < index; i++)
        {
            s.add(arr[i]);
        }
  
        // Calculate the sum of all
        // the elements of the set
        for (Integer itr : s)
        {
  
            sum = sum + itr;
        }
  
        // Compare whether the sum is equal to n or not,
        // if it is equal to n print the numbers
        if (sum == n) 
        {
            for (Integer i : s) 
            {
                System.out.print(i+" ");
            }
            System.out.println();
            return;
        }
    }
  
    // Find previous number stored in the array
    int prev = (index == 0) ? 1 : arr[index - 1];
  
    for (int k = prev; k <= n; k++) 
    {
  
        // Store all the numbers recursively
        // into the arr[]
        if(index < n)
        {
            arr[index] = k;
            findCombinationsUtil(arr, index + 1,
                            n, red_num - k);
              
        }
    }
}
  
// Function to find all the
// distinct combinations of n
static void findCombinations(int n)
{
    int []a = new int[n];
    findCombinationsUtil(a, 0, n, n);
}
  
// Driver code
public static void main(String arr[]) 
{
    int n = 7;
    findCombinations(n);
}
}
  
/* This code contributed by PrinciRaj1992 */

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
using System;
using System.Collections.Generic; 
  
class GFG 
{
  
/* arr[] to store all the distinct elements
    index - next location in array 
    num - given number 
    reducedNum - reduced number */
static void findCombinationsUtil(int []arr, int index,
                        int n, int red_num)
{
  
    // Set to store all the
    // distinct elements
    HashSet<int> s = new HashSet<int>();
    int sum = 0;
  
    // Base condition
    if (red_num < 0) 
    {
        return;
    }
  
    if (red_num == 0) 
    {
  
        // Iterate over all the elements
        // and store it into the set
        for (int i = 0; i < index; i++)
        {
            s.Add(arr[i]);
        }
  
        // Calculate the sum of all
        // the elements of the set
        foreach (int itr in s)
        {
  
            sum = sum + itr;
        }
  
        // Compare whether the sum is equal to n or not,
        // if it is equal to n print the numbers
        if (sum == n) 
        {
            foreach (int i in s)
            {
                Console.Write(i+" ");
            }
            Console.WriteLine();
            return;
        }
    }
  
    // Find previous number stored in the array
    int prev = (index == 0) ? 1 : arr[index - 1];
  
    for (int k = prev; k <= n; k++) 
    {
  
        // Store all the numbers recursively
        // into the arr[]
        if(index < n)
        {
            arr[index] = k;
            findCombinationsUtil(arr, index + 1,
                            n, red_num - k);
              
        }
    }
}
  
// Function to find all the
// distinct combinations of n
static void findCombinations(int n)
{
    int []a = new int[n];
    findCombinationsUtil(a, 0, n, n);
}
  
// Driver code
public static void Main(String []arr) 
{
    int n = 7;
    findCombinations(n);
}
}
  
// This code contributed by Rajput-Ji

chevron_right


Output:

1 2 4 
1 6 
2 5 
3 4 
7


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : princiraj1992, Rajput-Ji