Generate all k-number combinations with sum n

Last Updated : 7 Oct, 2025

Given two integers, n and k, find all possible unique combinations of k numbers whose sum equals n. Only numbers from 1 to 9 can be used, and each number may appear at most once in a combination. The order of numbers does not matter.

Examples:

Input: n = 9, k = 3
Output: [[1, 2, 6], [1, 3, 5], [2, 3, 4]]
Explanation: There are three valid combinations of 3 numbers that sum to 9 — [1, 2, 6], [1, 3, 5], and [2, 3, 4].

Input: n = 3, k = 3
Output: []
Explanation: It is not possible to pick 3 distinct numbers from 1 to 9 whose sum is 3, so no valid combinations exist.

Try It Yourself
redirect icon

[Approach] - Using Backtracking

The problem can be solved using backtracking by exploring numbers from 1 to 9 and building combinations step by step. At each stage, we pick a number, reduce the remaining target sum n and the required count k, and recursively search further. If both n and k reach zero, we have found a valid combination. If either becomes negative, we backtrack and try another option.

C++
#include <iostream>
#include <vector>
using namespace std;

// Recursive function to find all valid combinations
void findCombinations(int n, int k, vector<int>& subVector,
                      vector<vector<int>>& res, int last) {
                          
    // Base case: if exact sum and exact count achieved
    if (n == 0 && k == 0) {
        res.push_back(subVector);
        return;
    }

    // If sum or count becomes negative, backtrack
    if (n < 0 || k < 0)
        return;

    // Try numbers from 'last' to 9
    for (int i = last; i <= 9; i++) {
    
        // Choose the number
        subVector.push_back(i);              
        findCombinations(n - i, k - 1, subVector, res, i + 1);
        
        // Backtrack
        subVector.pop_back();                 
    }
}

// Function to generate and print all combinations
vector<vector<int>> combinationSum(int n, int k) {
    
    // Check if combination is impossible
    // Maximum sum can be 45 (1+2+3+4 .... 9)
    if (n < k || n > 45) {
        return {};
    }
    
    vector<int> subVector;  
    
    vector<vector<int>> res;            

    findCombinations(n, k, subVector, res, 1); 
    
    return res;
}

int main() {
    int n = 9, k = 3;
    vector<vector<int>> ans = combinationSum(n, k);
    
    for (auto &comb : ans) {
        for (int x : comb)
            cout << x << " ";
        cout << endl;
    }

    return 0;
}
Java
import java.util.ArrayList;

class GFG {

    // Recursive function to find all valid combinations
    static void findCombinations(int n, int k, ArrayList<Integer> subVector,
                                        ArrayList<ArrayList<Integer>> res, int last) {

        // Base case: if exact sum and exact count achieved
        if (n == 0 && k == 0) {
            res.add(new ArrayList<>(subVector));
            return;
        }

        // If sum or count becomes negative, backtrack
        if (n < 0 || k < 0)
            return;

        // Try numbers from 'last' to 9
        for (int i = last; i <= 9; i++) {

            // Choose the number
            subVector.add(i);
            findCombinations(n - i, k - 1, subVector, res, i + 1);

            // Backtrack
            subVector.remove(subVector.size() - 1);
        }
    }

    // Function to generate and print all combinations
    static ArrayList<ArrayList<Integer>> combinationSum(int n, int k) {

        // Check if combination is impossible
         // Maximum sum can be 45 (1+2+3+4 .... 9)
        if (n < k || n > 45) {
            return new ArrayList<>();
        }

        ArrayList<Integer> subVector = new ArrayList<>();
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();

        findCombinations(n, k, subVector, res, 1);

        return res;
    }

    public static void main(String[] args) {
        int n = 9, k = 3;
        ArrayList<ArrayList<Integer>> ans = combinationSum(n, k);

        for (ArrayList<Integer> comb : ans) {
            for (int x : comb)
                System.out.print(x + " ");
            System.out.println();
        }
    }
}
Python
# Recursive function to find all valid combinations
def findCombinations(n, k, subVector, res, last):

    # Base case: if exact sum and exact count achieved
    if n == 0 and k == 0:
        res.append(subVector[:])
        return

    # If sum or count becomes negative, backtrack
    if n < 0 or k < 0:
        return

    # Try numbers from 'last' to 9
    for i in range(last, 10):

        # Choose the number
        subVector.append(i)
        findCombinations(n - i, k - 1, subVector, res, i + 1)

        # Backtrack
        subVector.pop()


# Function to generate and print all combinations
def combinationSum(n, k):

    # Check if combination is impossible
    #  Maximum sum can be 45 (1+2+3+4 .... 9)
    if n < k or n > 45:
        return []

    subVector = []
    res = []

    findCombinations(n, k, subVector, res, 1)
    return res

if __name__ == "__main__":
    n, k = 9, 3
    ans = combinationSum(n, k)
    for comb in ans:
        print(*comb)
C#
using System;
using System.Collections.Generic;

class GFG {

    // Recursive function to find all valid combinations
    static void findCombinations(int n, int k, List<int> subVector,
                                        List<List<int>> res, int last) {

        // Base case: if exact sum and exact count achieved
        if (n == 0 && k == 0) {
            res.Add(new List<int>(subVector));
            return;
        }

        // If sum or count becomes negative, backtrack
        if (n < 0 || k < 0)
            return;

        // Try numbers from 'last' to 9
        for (int i = last; i <= 9; i++) {

            // Choose the number
            subVector.Add(i);
            findCombinations(n - i, k - 1, subVector, res, i + 1);

            // Backtrack
            subVector.RemoveAt(subVector.Count - 1);
        }
    }

    // Function to generate and print all combinations
    static List<List<int>> combinationSum(int n, int k) {

        // Check if combination is impossible
         // Maximum sum can be 45 (1+2+3+4 .... 9)
        if (n < k || n > 45)
            return new List<List<int>>();

        List<int> subVector = new List<int>();
        List<List<int>> res = new List<List<int>>();

        findCombinations(n, k, subVector, res, 1);
        return res;
    }

    static void Main() {
        int n = 9, k = 3;
        var ans = combinationSum(n, k);

        foreach (var comb in ans) {
            Console.WriteLine(string.Join(" ", comb));
        }
    }
}
JavaScript
// Recursive function to find all valid combinations
function findCombinations(n, k, subVector, res, last) {

    // Base case: if exact sum and exact count achieved
    if (n === 0 && k === 0) {
        res.push([...subVector]);
        return;
    }

    // If sum or count becomes negative, backtrack
    if (n < 0 || k < 0)
        return;

    // Try numbers from 'last' to 9
    for (let i = last; i <= 9; i++) {

        // Choose the number
        subVector.push(i);
        findCombinations(n - i, k - 1, subVector, res, i + 1);

        // Backtrack
        subVector.pop();
    }
}

// Function to generate and print all combinations
function combinationSum(n, k) {

    // Check if combination is impossible
     // Maximum sum can be 45 (1+2+3+4 .... 9)
    if (n < k || n > 45)
        return [];

    let subVector = [];
    let res = [];

    findCombinations(n, k, subVector, res, 1);
    return res;
}

// Driver code
let n = 9, k = 3;
let ans = combinationSum(n, k);

for (let comb of ans) {
    console.log(comb.join(" "));
}

Output
1 2 6 
1 3 5 
2 3 4 

Time Complexity: O(k × C(9, k)), because there are C(9, k) valid combinations of size k, and copying each combination into the result takes O(k) time
Auxiliary Space: O(k)

Comment