题意:

image.png

解题思路:

  1. 思路:
  2. 优化剪枝
  3. 1. sort($candidates);
  4. 2. 剪枝: if ($i != $start && $candidates[$i] == $candidates[$i - 1]) continue;

PHP代码实现:

  1. class Solution {
  2. public $res = [];
  3. function combinationSum2($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 ($i != $start && $candidates[$i] == $candidates[$i - 1]) continue;
  16. array_push($array, $candidates[$i]);
  17. // 因为元素不可以重复使用,这里递归传递下去的是 i + 1 而不是 i
  18. $this->dfs($array, $candidates, $target - $candidates[$i], $i + 1);
  19. array_pop($array);
  20. }
  21. }
  22. }

GO代码实现:

  1. var res [][]int
  2. func combinationSum2(candidates []int, target int) [][]int {
  3. res = make([][]int, 0)
  4. sort.Ints(candidates)
  5. dfs(candidates, []int{}, target, 0)
  6. return res
  7. }
  8. func dfs(candidates, temp []int, target, start int) {
  9. if target < 0 { return }
  10. if target == 0 {
  11. res = append(res, append([]int{}, temp...))
  12. return
  13. }
  14. for i := start; i < len(candidates); i ++ {
  15. if i > start && candidates[i] == candidates[i - 1] {
  16. continue
  17. }
  18. temp = append(temp, candidates[i])
  19. dfs(candidates, temp, target - candidates[i], i + 1)
  20. temp = temp[:len(temp)-1]
  21. }
  22. }