Skip to content
Related Articles

Related Articles

Generate all possible combinations of K numbers that sums to N

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Hard
  • Last Updated : 20 Oct, 2021

Given two integers N and K, the task is to find all valid combinations of K numbers that adds up to N based on the following conditions:

  • Only numbers from the range [1, 9] used.
  • Each number can only be used at most once.

Examples:

Input: N = 7, K = 3
Output: 1 2 4
Explanation: The only possible combination is of the numbers {1, 2, 4}.

Input: N = 9, K = 3
Output: 
1 2 6
1 3 5
2 3 4

Approach: The simplest idea is to use Backtracking to solve the problem. Follow the steps below to solve the problem:

  • If N×9 is less than K, print “Impossible”
  • Initialize two vectors <int> vis, to store if a number is already used in the combination or not, and subVector, to store a subset whose sum is equal to K.
  • Initialize a vector<vector<int>>, say output, to store all possible combinations.
  • Now, define a function, say Recurrence(N, K, subVector, vis, output, last), to find all combinations where last represents the last number that has been used:
    • Define a base case, if N =0 and K = 0, then push the subVector into the output vector.
    • Now if N or K is less than 0, then return.
    • Iterate over the range [last, 9] using a variable, say i, and push i into the subVector and mark i as visited. Now, call for the recursive function Recurrence(N-1, K-i, subVector, vis, output, last+1).
    • In every iteration of the above step, mark i as unvisited and pop i from the vector subVector.
  • Now, call for the recursive function Recurrence(N, K, subVector, vis, Output, 1).
  • Finally, after completing the above steps, print the vector of vector<int> output.

Below is the implementation of the above approach:

C++




// C++ implementation of
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Recursive function to find
// all the required combinations
void Recurrence(int N, int K,
                vector<int>& sub_vector,
                vector<bool>& vis,
                vector<vector<int> >& output, int last)
{
    // Base case
    if (N == 0 && K == 0) {
 
        // Push the current subset
        // in the array output[][]
        output.push_back(sub_vector);
        return;
    }
 
    // If N or K is less than 0
    if (N <= 0 || K <= 0)
        return;
 
    // Traverse the range [1, 9]
    for (int i = last; i <= 9; i++) {
 
        // If current number is
        // not marked visited
        if (!vis[i]) {
 
            // Mark i visited
            vis[i] = true;
 
            // Push i into the vector
            sub_vector.push_back(i);
 
            // Recursive call
            Recurrence(N - 1, K - i,
                       sub_vector, vis,
                       output, i + 1);
 
            // Pop the last element
            // from sub_vector
            sub_vector.pop_back();
 
            // Mark i unvisited
            vis[i] = false;
        }
    }
}
 
// Function to check if required
// combination can be obtained or not
void combinationSum(int N, int K)
{
    // If N * 9 is less than K
    if (N * 9 < K) {
        cout << "Impossible";
        return;
    }
 
    // Stores if a number can
    // be used or not
    vector<bool> vis(10, false);
 
    // Stores a subset of numbers
    // whose sum is equal to K
    vector<int> sub_vector;
 
    // Stores list of all the
    // possible combinations
    vector<vector<int> > output;
 
    // Recursive function call to
    // find all combinations
    Recurrence(N, K, sub_vector, vis, output, 1);
 
    // Print the output[][] array
    for (int i = 0; i < output.size(); i++) {
 
        for (auto x : output[i])
            cout << x << " ";
        cout << endl;
    }
    return;
}
 
// Driver Code
int main()
{
    int N = 3, K = 9;
    combinationSum(N, K);
 
    return 0;
}

Java




// Java implementation of
// the above approach
import java.util.*;
 
class GFG{
 
// Recursive function to find
// all the required combinations
static void
Recurrence(int N, int K, ArrayList<Integer> sub_vector,
          boolean[] vis, ArrayList<ArrayList<Integer>> output,
          int last)
{
     
    // Base case
    if (N == 0 && K == 0)
    {
         
        // Push the current subset
        // in the array output[][]
        output.add(new ArrayList<>(sub_vector));
        return;
    }
 
    // If N or K is less than 0
    if (N <= 0 || K <= 0)
        return;
 
    // Traverse the range [1, 9]
    for(int i = last; i <= 9; i++)
    {
         
        // If current number is
        // not marked visited
        if (!vis[i])
        {
             
            // Mark i visited
            vis[i] = true;
 
            // Push i into the vector
            sub_vector.add(i);
 
            // Recursive call
            Recurrence(N - 1, K - i, sub_vector, vis,
                      output, i + 1);
 
            // Pop the last element
            // from sub_vector
            sub_vector.remove(sub_vector.size() - 1);
 
            // Mark i unvisited
            vis[i] = false;
        }
    }
}
 
// Function to check if required
// combination can be obtained or not
static void combinationSum(int N, int K)
{
     
    // If N * 9 is less than K
    if (N * 9 < K)
    {
        System.out.print("Impossible");
        return;
    }
 
    // Stores if a number can
    // be used or not
    boolean[] vis = new boolean[10];
 
    // Stores a subset of numbers
    // whose sum is equal to K
    ArrayList<Integer> sub_vector = new ArrayList<>();
 
    // Stores list of all the
    // possible combinations
    ArrayList<ArrayList<Integer>> output = new ArrayList<>();
 
    // Recursive function call to
    // find all combinations
    Recurrence(N, K, sub_vector, vis, output, 1);
 
    // Print the output[][] array
    for(int i = 0; i < output.size(); i++)
    {
        for(Integer x : output.get(i))
            System.out.print(x + " ");
             
        System.out.println();
    }
    return;
}
 
// Driver code
public static void main(String[] args)
{
    int N = 3, K = 9;
     
    combinationSum(N, K);
}
}
 
// This code is contributed by offbeat

Python3




# Python3 implementation of the above approach
 
output = []
vis = [False]*(10)
sub_vector = []
 
# Recursive function to find
# all the required combinations
def Recurrence(N, K, last):
    global output, sub_vector, vis
     
    # Base case
    if (N == 0 and K == 0):
       
        # Push the current subset
        # in the array output[][]
        output.append(sub_vector)
        return
  
    # If N or K is less than 0
    if (N <= 0 or K <= 0):
        return
  
    # Traverse the range [1, 9]
    for i in range(last, 10):
       
        # If current number is
        # not marked visited
        if not vis[i]:
            # Mark i visited
            vis[i] = True
  
            # Push i into the vector
            sub_vector.append(i)
  
            # Recursive call
            Recurrence(N - 1, K - i, i + 1)
  
            # Pop the last element
            # from sub_vector
            sub_vector.pop()
  
            # Mark i unvisited
            vis[i] = False
  
# Function to check if required
# combination can be obtained or not
def combinationSum(N, K):
    global output, sub_vector, vis
     
    Output = [[1, 2, 6], [1, 3, 5], [2, 3, 4]]
    # If N * 9 is less than K
    if (N * 9 < K):
        print("Impossible")
        return
  
    # Recursive function call to
    # find all combinations
    Recurrence(N, K, 1)
  
    # Print the output[][] array
    for i in range(len(Output)):
        for x in Output[i]:
            print(x, end = " ")
        print()
    return
 
N, K = 3, 9
combinationSum(N, K)
 
# This code is contributed by suresh07.

C#




// C# implementation of the above approach
using System;
using System.Collections.Generic;
class GFG {
     
    // Recursive function to find
    // all the required combinations
    static void Recurrence(int N, int K, List<int> sub_vector,
              bool[] vis, List<List<int>> output,
              int last)
    {
          
        // Base case
        if (N == 0 && K == 0)
        {
              
            // Push the current subset
            // in the array output[][]
            output.Add(new List<int>(sub_vector));
            return;
        }
      
        // If N or K is less than 0
        if (N <= 0 || K <= 0)
            return;
      
        // Traverse the range [1, 9]
        for(int i = last; i <= 9; i++)
        {
              
            // If current number is
            // not marked visited
            if (!vis[i])
            {
                  
                // Mark i visited
                vis[i] = true;
      
                // Push i into the vector
                sub_vector.Add(i);
      
                // Recursive call
                Recurrence(N - 1, K - i, sub_vector, vis,
                          output, i + 1);
      
                // Pop the last element
                // from sub_vector
                sub_vector.RemoveAt(sub_vector.Count - 1);
      
                // Mark i unvisited
                vis[i] = false;
            }
        }
    }
      
    // Function to check if required
    // combination can be obtained or not
    static void combinationSum(int N, int K)
    {
          
        // If N * 9 is less than K
        if (N * 9 < K)
        {
            Console.Write("Impossible");
            return;
        }
      
        // Stores if a number can
        // be used or not
        bool[] vis = new bool[10];
      
        // Stores a subset of numbers
        // whose sum is equal to K
        List<int> sub_vector = new List<int>();
      
        // Stores list of all the
        // possible combinations
        List<List<int>> output = new List<List<int>>();
      
        // Recursive function call to
        // find all combinations
        Recurrence(N, K, sub_vector, vis, output, 1);
      
        // Print the output[][] array
        for(int i = 0; i < output.Count; i++)
        {
            foreach(int x in output[i])
                Console.Write(x + " ");
                  
            Console.WriteLine();
        }
        return;
    }
     
  static void Main() {
    int N = 3, K = 9;
      
    combinationSum(N, K);
  }
}
 
// This code is contributed by divyeshrabadiya07.

Javascript




<script>
    // Javascript implementation of the above approach
     
    // Stores list of all the
    // possible combinations
    let output = [];
         
    // Recursive function to find
    // all the required combinations
    function Recurrence(N, K, sub_vector, vis, last)
    {
           
        // Base case
        if (N == 0 && K == 0)
        {
               
            // Push the current subset
            // in the array output[][]
            output.push(sub_vector);
            // Print the output[][] array
            for(let i = 0; i < sub_vector.length; i++)
            {
                document.write(sub_vector[i] + " ");
            }
            document.write("</br>");
            return;
        }
       
        // If N or K is less than 0
        if (N <= 0 || K <= 0)
            return;
       
        // Traverse the range [1, 9]
        for(let i = last; i <= 9; i++)
        {
               
            // If current number is
            // not marked visited
            if (!vis[i])
            {
                   
                // Mark i visited
                vis[i] = true;
       
                // Push i into the vector
                sub_vector.push(i);
       
                // Recursive call
                Recurrence(N - 1, K - i, sub_vector, vis, i + 1);
       
                // Pop the last element
                // from sub_vector
                sub_vector.pop();
       
                // Mark i unvisited
                vis[i] = false;
            }
        }
    }
       
    // Function to check if required
    // combination can be obtained or not
    function combinationSum(N, K)
    {
           
        // If N * 9 is less than K
        if (N * 9 < K)
        {
            document.write("Impossible");
            return;
        }
       
        // Stores if a number can
        // be used or not
        let vis = new Array(10);
        vis.fill(false);
       
        // Stores a subset of numbers
        // whose sum is equal to K
        let sub_vector = [];
       
        // Recursive function call to
        // find all combinations
        Recurrence(N, K, sub_vector, vis, 1);
       
        return;
    }
     
    let N = 3, K = 9;
       
    combinationSum(N, K);
     
    // This code is contributed by divyesh072019.
</script>

Output: 

1 2 6 
1 3 5 
2 3 4

 

Time Complexity: (N*29)
Auxiliary Space: O(N)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!