class Solution {
public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> results = new ArrayList<>();
Arrays.sort(candidates);
dfs(candidates, target, 0, results, new ArrayList<Integer>());
return results;
}
public static void dfs(int[] candidates, int target, int index, List<List<Integer>> results, List<Integer> cur){
if (target == 0){
results.add(new ArrayList<Integer>(cur));
} else if (target > 0){
for (int i = index; i < candidates.length; i++){
if (candidates[i] > target){
break;
}
// 判断不是 初始进来(防止数组越界) 而且 连续两个不相等才行
if (i != index && candidates[i] == candidates[i - 1]){
continue;
}
cur.add(candidates[i]);
//这里一定是 i + 1 因为不让重复
dfs(candidates, target - candidates[i], i + 1, results, cur);
cur.remove(cur.size() - 1);
}
}
}
}
leetcode40,组合总和2(不允许重复)
最新推荐文章于 2022-01-18 08:26:26 发布