40.go 827 B

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