40.go 828 B

1234567891011121314151617181920212223242526272829303132333435
  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. func combinationSum2Iter(candidates []int, target int, last []int, beg int, res *[][]int) {
  7. if target == 0 {
  8. *res = append(*res, last)
  9. return
  10. }
  11. for i := beg; i < len(candidates) && candidates[i] <= target; i++ {
  12. // method to remove duplicated solutions
  13. if i > beg && candidates[i] == candidates[i-1] {
  14. continue
  15. }
  16. solution := make([]int, len(last))
  17. copy(solution, last)
  18. solution = append(solution, candidates[i])
  19. combinationSum2Iter(candidates, target-candidates[i], solution, i+1, res)
  20. }
  21. }
  22. func combinationSum2(candidates []int, target int) [][]int {
  23. res := make([][]int, 0)
  24. sort.Ints(candidates)
  25. combinationSum2Iter(candidates, target, []int{}, 0, &res)
  26. return res
  27. }
  28. func main() {
  29. a1 := []int{10, 1, 2, 7, 6, 1, 5}
  30. fmt.Println(combinationSum2(a1, 8))
  31. }