How to find the unique combination k sum that corresponds to k sum using C#?

The k-sum combination problem involves finding all unique combinations of exactly k numbers from a given range that sum up to a specific target value. This is solved using backtracking, which explores all possible combinations while pruning invalid paths early.

The algorithm maintains two lists: an output list to store valid combinations and a currentList to track the current combination being explored. The backtracking function recursively explores combinations, adding numbers one by one until either the target sum is achieved with exactly k numbers, or the constraints are violated.

How It Works

The backtracking algorithm follows these steps −

  • Base Case: If the current sum equals the target and we have exactly k numbers, add the combination to results.

  • Pruning: If the sum exceeds the target or we have k numbers but wrong sum, backtrack immediately.

  • Exploration: For each remaining number, add it to the current combination, recurse, then remove it (backtrack).

Backtracking Tree (target=5, k=2) [] [1] [2] [3] [1,4] [1,...] [2,3] [3,...] ? Valid ? Valid ? Prune ? Prune

Example

The following example finds all combinations of exactly 2 numbers from the range [1, 2, 3, 4] that sum to 5 −

using System;
using System.Collections.Generic;

public class KSumCombination {
    public void FindUniqueCombinations(int target, int k) {
        // Create array [1, 2, 3, 4] for target 5
        int[] numbers = new int[target];
        for (int i = 0; i < target - 1; i++) {
            numbers[i] = i + 1;
        }
        
        List<int> currentCombination = new List<int>();
        List<List<int>> results = new List<List<int>>();
        
        Backtrack(numbers, target, k, 0, 0, currentCombination, results);
        
        Console.WriteLine($"Combinations of {k} numbers that sum to {target}:");
        foreach (var combination in results) {
            Console.WriteLine("[" + string.Join(", ", combination) + "]");
        }
    }
    
    private void Backtrack(int[] numbers, int target, int k, int startIndex, 
                          int currentSum, List<int> current, List<List<int>> results) {
        // Base case: found valid combination
        if (currentSum == target && current.Count == k) {
            results.Add(new List<int>(current));
            return;
        }
        
        // Pruning conditions
        if (currentSum > target || current.Count == k) {
            return;
        }
        
        // Explore remaining numbers
        for (int i = startIndex; i < numbers.Length; i++) {
            current.Add(numbers[i]);
            Backtrack(numbers, target, k, i + 1, currentSum + numbers[i], current, results);
            current.RemoveAt(current.Count - 1); // Backtrack
        }
    }
}

class Program {
    static void Main(string[] args) {
        KSumCombination solver = new KSumCombination();
        solver.FindUniqueCombinations(5, 2);
        
        Console.WriteLine();
        solver.FindUniqueCombinations(6, 3);
    }
}

The output of the above code is −

Combinations of 2 numbers that sum to 5:
[1, 4]
[2, 3]

Combinations of 3 numbers that sum to 6:
[1, 2, 3]

Algorithm Complexity

Aspect Complexity Explanation
Time O(C(n,k)) Explores all combinations of k elements from n numbers
Space O(k) Recursion depth and current combination storage

Key Features

The backtracking approach provides several advantages −

  • Early Pruning: Stops exploring paths when sum exceeds target or k numbers are reached.

  • Memory Efficient: Uses a single current list that gets modified and restored during backtracking.

  • Guaranteed Uniqueness: By using ascending order and never revisiting previous elements, duplicate combinations are avoided.

Conclusion

The k-sum combination problem is efficiently solved using backtracking with pruning. This approach systematically explores all valid combinations while avoiding duplicate solutions and unnecessary computations through early termination conditions.

Updated on: 2026-03-17T07:04:36+05:30

356 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements