12345678910111213141516171819202122 |
- func combinationSum3(k int, n int) (ans [][]int) {
- stack := make([]int, 0)
- for i, sum, l := 1, 0, 0; ; l = len(stack) {
- // If need to backtrack
- if l == k || 10-i+l < k { // Cut the branches or MLE
- if l == 0 { // No previous number to pop
- break
- } else if l == k && sum == n {
- ans = append(ans, make([]int, k))
- copy(ans[len(ans)-1], stack)
- }
- sum -= stack[l-1]
- i = stack[l-1] + 1
- stack = stack[:l-1]
- } else {
- stack = append(stack, i)
- sum += i
- i++
- }
- }
- return ans
- }
|