Skip to content
Related Articles

Related Articles

Generate all possible combinations of K numbers that sums to N
  • Difficulty Level : Hard
  • Last Updated : 05 Apr, 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 elemnet
            // 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 elemnet
            // 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
Output: 
1 2 6 
1 3 5 
2 3 4

 

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

 

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :