Question
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
给出一个候选数字集合C和目标值T,请你找出所有C中元素相加得到T的组合。(每个元素只能使用一次,且C中有相同元素)
Example
given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
Solution
回溯解。因为元素不能多次使用,所以在回溯过程中,每次从下个元素的索引开始,而又因为C中有相同元素,所以我们需要先对数组进行排序,然后每当遇到第二个相同元素作为起始点时则跳过不做计算
public class Solution { public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); List<List<Integer>> res = new ArrayList<>(); backtracking(candidates, 0, target, res, new ArrayList<>()); return res; } public void backtracking(int[] candidates, int start, int target, List<List<Integer>> res, List<Integer> temp){ if(target < 0) return; if(target == 0){ res.add(new ArrayList<>(temp)); return; } for(int i = start; i < candidates.length; i++){ // 如果出现重复元素,第二个元素直接跳过 if(i > start && candidates[i] == candidates[i - 1]) continue; // 仅当当前元素小于目标值时选择 if(candidates[i] <= target) { temp.add(candidates[i]); // 每次指向下一个元素的索引 backtracking(candidates, i + 1, target - candidates[i], res, temp); temp.remove(temp.size() - 1); } } } }