216.combination-sum-iii.go 512 B

12345678910111213141516171819202122
  1. func combinationSum3(k int, n int) (ans [][]int) {
  2. stack := make([]int, 0)
  3. for i, sum, l := 1, 0, 0; ; l = len(stack) {
  4. // If need to backtrack
  5. if l == k || 10-i+l < k { // Cut the branches or MLE
  6. if l == 0 { // No previous number to pop
  7. break
  8. } else if l == k && sum == n {
  9. ans = append(ans, make([]int, k))
  10. copy(ans[len(ans)-1], stack)
  11. }
  12. sum -= stack[l-1]
  13. i = stack[l-1] + 1
  14. stack = stack[:l-1]
  15. } else {
  16. stack = append(stack, i)
  17. sum += i
  18. i++
  19. }
  20. }
  21. return ans
  22. }