题意:
解题思路:
思路:
优化剪枝
1. sort($candidates);
2. 剪枝: if ($i != $start && $candidates[$i] == $candidates[$i - 1]) continue;
PHP代码实现:
class Solution {
public $res = [];
function combinationSum2($candidates, $target) {
sort($candidates);
$this->dfs([], $candidates, $target, 0);
return $this->res;
}
function dfs($array, $candidates, $target, $start) {
if ($target < 0) return;
if ($target == 0) {
array_push($this->res, $array);
return;
}
for ($i = $start; $i < count($candidates); $i++) {
if ($i != $start && $candidates[$i] == $candidates[$i - 1]) continue;
array_push($array, $candidates[$i]);
// 因为元素不可以重复使用,这里递归传递下去的是 i + 1 而不是 i
$this->dfs($array, $candidates, $target - $candidates[$i], $i + 1);
array_pop($array);
}
}
}
GO代码实现:
var res [][]int
func combinationSum2(candidates []int, target int) [][]int {
res = make([][]int, 0)
sort.Ints(candidates)
dfs(candidates, []int{}, target, 0)
return res
}
func dfs(candidates, temp []int, target, start int) {
if target < 0 { return }
if target == 0 {
res = append(res, append([]int{}, temp...))
return
}
for i := start; i < len(candidates); i ++ {
if i > start && candidates[i] == candidates[i - 1] {
continue
}
temp = append(temp, candidates[i])
dfs(candidates, temp, target - candidates[i], i + 1)
temp = temp[:len(temp)-1]
}
}