This post is completed by 1 user
|
Add to List |
436. Find all unique combinations of exact K numbers (from 1 to 9 ) with sum to N
Objective: Given two integers N and K. Write an algorithm to find all the combinations of k numbers which sum to N.
Conditions:
- All K numbers must be between 1 and 9 and unique.
- All numbers in K are positive.
Example:
N= 5 K=2 Output: [1, 4] [2, 3] N =12 K=3 Output: [1, 2, 9] [1, 3, 8] [1, 4, 7] [1, 5, 6] [2, 3, 7] [2, 4, 6] [3, 4, 5]
Approach: Use Recursion
- Given N and K.
- Start with sum = 0, start = 1, combinationList=null
- Iterate through i = start to 9.
- Add i to sum.
- Put i to combinationList.
- Make a recursive call with K-1 and start = start + 1 (to avoid duplicates) and combinationList.
- In tail recursion, backtrack and remove i from the combinationList to find more solutions
- Base case: If K=0, check if sum=N, Print combinationList.
Output:
N = 12 K = 3 [1, 2, 9] [1, 3, 8] [1, 4, 7] [1, 5, 6] [2, 3, 7] [2, 4, 6] [3, 4, 5]