題目描述
給定一個候選人編號的集合 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和為 target 的組合。
candidates 中的每個數字在每個組合中只能使用 一次 。
注意:解集不能包含重復的組合。
輸入示例
candidates = [10,1,2,7,6,1,5], target = 8,
輸出示例
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
解題代碼文章來源:http://www.zghlxwxcb.cn/news/detail-819307.html
class Solution {
List<List<Integer>> result = new ArrayList<>();
Deque<Integer> path = new ArrayDeque<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
int n = candidates.length;
boolean[] used = new boolean[n];
backtrack(candidates, target, 0, 0, used);
return result;
}
public void backtrack(int[] candidates, int targetSum, int sum, int begin, boolean[] used) {
if(sum > targetSum) {
return;
}
if(sum == targetSum) {
result.add(new ArrayList<Integer>(path));
return;
}
for(int i = begin; i < candidates.length; i++) {
if(i > 0 && candidates[i] == candidates[i-1] && used[i-1] == false) {
continue;
}
path.addLast(candidates[i]);
sum += candidates[i];
used[i] = true;
backtrack(candidates, targetSum, sum, i+1, used);
used[i] = false;
sum -= candidates[i];
path.removeLast();
}
}
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-819307.html
到了這里,關于40. 組合總和 II - 力扣(LeetCode)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!