📑 题目:39. 组合总和

🚀 本题 LeetCode 传送门

题目大意

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

解题思路

  • 题目要求出总和为 sum 的所有组合,组合需要去重。
  • 这一题和第 47 题类似,只不过元素可以反复使用。

代码

  1. package leetcode
  2. import ""sort""
  3. func combinationSum(candidates []int, target int) [][]int {
  4. if len(candidates) == 0 {
  5. return [][]int{}
  6. }
  7. c, res := []int{}, [][]int{}
  8. sort.Ints(candidates)
  9. findcombinationSum(candidates, target, 0, c, &res)
  10. return res
  11. }
  12. func findcombinationSum(nums []int, target, index int, c []int, res *[][]int) {
  13. if target <= 0 {
  14. if target == 0 {
  15. b := make([]int, len(c))
  16. copy(b, c)
  17. *res = append(*res, b)
  18. }
  19. return
  20. }
  21. for i := index; i < len(nums); i++ {
  22. if nums[i] > target { // 这里可以剪枝优化
  23. break
  24. }
  25. c = append(c, nums[i])
  26. findcombinationSum(nums, target-nums[i], i, c, res) // 注意这里迭代的时候 index 依旧不变,因为一个元素可以取多次
  27. c = c[:len(c)-1]
  28. }
  29. }