class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
//首先将数组排序
Arrays.sort(candidates);
ArrayList<List<Integer>> result = new ArrayList<>();
dfs(candidates, target, result, new ArrayList<Integer>(), 0, 0);
return result;
}
private void dfs(int[] candidates, int target, List<List<Integer>> result, List<Integer> temp, int position, int sum) {
if (sum > target)
return;
if (sum == target) {
result.add(new ArrayList<>(temp));
return;
}
//如果当前位置超过长度结束
//放到这里来判断是因为每一次判断总和实际上都是在下一层才进行判断,所以先判断总和,避免最后一个数字没判断到
if (position == candidates.length)
return;
//走到这里说明这条分支还要继续走下去
for (int i = position; i < candidates.length; i++) {
//i > position就可以避免当前层出现重复
if (i > position && candidates[i] == candidates[i - 1])
continue;
temp.add(candidates[i]);
dfs(candidates, target, result, temp, i + 1, sum + candidates[i]);
//删除
temp.remove(temp.size() - 1);
}
}
}
10-14
534
06-20
876
09-16
315