Open In App

Generate all possible combinations of K numbers that sums to N

Last Updated : 07 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 NX9 is less than K, print “Impossible”
  • Initialize two arrays 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 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 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


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




// 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.


Python3




# Python implementation of the above approach
 
# Recursive function to find
# all the required combinations
def Recurrence(N, K, sub_vector, vis, output, last):
    # 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, sub_vector, vis, output, 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):
    # If N * 9 is less than K
    if N * 9 < K:
        print("Impossible")
        return
 
    # Stores if a number can
    # be used or not
    vis = [False] * 10
 
    # Stores a subset of numbers
    # whose sum is equal to K
    sub_vector = []
 
    # Stores list of all the
    # possible combinations
    output = []
 
    # Recursive function call to
    # find all combinations
    Recurrence(N, K, sub_vector, vis, output, 1)
 
    # Print the output array
    for i in range(len(output)):
        for x in output[i]:
            print(x, end=" ")
        print()
    return
 
 
# Driver Code
if __name__ == "__main__":
    N, K = 3, 9
    combinationSum(N, K)


Output

1 2 6 
1 3 5 
2 3 4

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

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads