题意:

image.png

解题思路:

  1. 思路:
  2. 优化剪枝
  3. 1. sort($candidates);
  4. 2. if ($candidates[$i] > $target) break;
  5. 3. 传入 i 而不是 i+1 是为了数字能重复使用;

PHP代码实现:

  1. class Solution {
  2. public $res = [];
  3. function combinationSum($candidates, $target) {
  4. sort($candidates);
  5. $this->dfs([], $candidates, $target, 0);
  6. return $this->res;
  7. }
  8. function dfs($array, $candidates, $target, $start) {
  9. if ($target < 0) return;
  10. if ($target == 0) {
  11. array_push($this->res, $array);
  12. return;
  13. }
  14. for ($i = $start; $i < count($candidates); $i++) {
  15. if ($candidates[$i] > $target) break;
  16. array_push($array, $candidates[$i]);
  17. $this->dfs($array, $candidates, $target - $candidates[$i], $i);
  18. array_pop($array);
  19. }
  20. }
  21. }

GO代码实现:

  1. var res [][]int
  2. func combinationSum(candidates []int, target int) [][]int {
  3. res = make([][]int, 0)
  4. dfs(candidates, []int{}, target, 0)
  5. return res
  6. }
  7. func dfs(candidates, temp []int, target, start int) {
  8. if target < 0 { return }
  9. if target == 0 {
  10. res = append(res, append([]int{}, temp...))
  11. return
  12. }
  13. for i := start; i < len(candidates); i ++ {
  14. temp = append(temp, candidates[i])
  15. // 这里传入 i 而不是 i+1 是为了数字能重复使用
  16. // i+1 数字就无法重复使用
  17. dfs(candidates, temp, target - candidates[i], i)
  18. temp = temp[:len(temp)-1]
  19. }
  20. }