216. Combination Sum III #
Problem #
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Note:
- All numbers will be positive integers.
- The solution set must not contain duplicate combinations.
Example 1:
Input: k = 3, n = 7
Output: [[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]
Summary #
Find all combinations of k numbers that add up to n. Each combination may only contain positive integers from 1 - 9, and no combination contains duplicate numbers.
Note:
- All numbers are positive integers.
- The solution set must not contain duplicate combinations.
Solution Approach #
- This problem is even simpler than Problem 39; with a slight modification to the solution for Problem 39, this problem can be solved.
- In Problem 39, an array is given; in this problem, the array is fixed as [1,2,3,4,5,6,7,8,9], and numbers cannot be reused.
Code #
package leetcode
func combinationSum3(k int, n int) [][]int {
if k == 0 {
return [][]int{}
}
c, res := []int{}, [][]int{}
findcombinationSum3(k, n, 1, c, &res)
return res
}
func findcombinationSum3(k, target, index int, c []int, res *[][]int) {
if target == 0 {
if len(c) == k {
b := make([]int, len(c))
copy(b, c)
*res = append(*res, b)
}
return
}
for i := index; i < 10; i++ {
if target >= i {
c = append(c, i)
findcombinationSum3(k, target-i, i+1, c, res)
c = c[:len(c)-1]
}
}
}