代码如下:
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
// 最终返回 retList
List<List<Integer>> retList = new ArrayList<>();
// 先将原数组排序
Arrays.sort(candidates);
// 封装函数combinationSum2Helper()
combinationSum2Helper(retList,candidates,target,0,0,new ArrayList<>(),-1);
return retList;
}
/**
* combinationSum2Helper()
* @param retList
* @param candidates
* @param target
* @param index 当前元素下标
* @param sum 临时链表元素和,用于和target 比较
* @param tmpList 临时链表
* @param pre 当前元素的前一个元素
*/
private void combinationSum2Helper(List<List<Integer>> retList, int[] candidates, int target, int index, int sum, ArrayList<Integer> tmpList, int pre) {
// 当 sum == target 时说明tmpList 满足题意,将tmpList加入retList直接返回
if(sum == target){
retList.add(new ArrayList<>(tmpList));
return;
}
// 此时tmpList不满足继续添加元素
for (int i = index; i < candidates.length; i++) {
// 如果当前sum + candidates[i] > target 不符合直接返回
if(sum + candidates[i] > target){
return;
}
// 如果 pre == candidates[i] 说明此处出现重复元素,跳过,在下次递归过程中处理
if(pre == candidates[i]){
continue;
}else{
pre = candidates[i];
}
// 回溯处理
tmpList.add(candidates[i]);
combinationSum2Helper(retList,candidates,target,i + 1,sum + candidates[i],tmpList,-1);
tmpList.remove(tmpList.size() - 1);
}
}