Tutorialspoint
Problem
Solution
Submissions

Combinations of K Numbers that Sum to N

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 12

Write a C# program to implement the FindCombinations function, which finds all possible combinations of k numbers that sum to n. The function should return a list of all possible k combinations that add up to n. Numbers can only be used once in each combination.

Example 1
  • Input: k = 3, n = 7
  • Output: [[1,2,4]]
  • Explanation:
    • There is only one valid combination: 1 + 2 + 4 = 7
Example 2
  • Input: k = 3, n = 9
  • Output: [[1,2,6], [1,3,5], [2,3,4]]
  • Explanation:
    • These are all valid combinations:
    • 1 + 2 + 6 = 9
    • 1 + 3 + 5 = 9
    • 2 + 3 + 4 = 9
Constraints
  • 1 ≤ k ≤ 9
  • 1 ≤ n ≤ 60
  • All numbers used must be positive integers
  • Each combination should contain exactly k unique numbers
  • Time Complexity: O(C(9,k) * k) where C(9,k) is the binomial coefficient
  • Space Complexity: O(k) for the recursion depth
NumberBacktracking AccenturePwC
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use backtracking to explore all possible combinations
  • Start with an empty combination and recursively add numbers
  • Maintain a current sum to avoid unnecessary calculations
  • Prune branches where the sum exceeds the target
  • When the combination size reaches k, check if the sum equals n

Steps to solve by this approach:

 Step 1: Create a backtracking function that builds combinations one element at a time
 Step 2: Use parameters to track the current combination, starting point, remaining elements needed (k), and remaining sum
 Step 3: When the combination reaches size k, check if the sum equals the target n
 Step 4: For each recursive call, try adding numbers from the current start position up to 9
 Step 5: Optimize by skipping numbers that would make the sum exceed the target
 Step 6: After exploring with a number added, remove it (backtrack) to try other possibilities
 Step 7: Return all valid combinations found during the process

Submitted Code :