LeetCode 40. Combination Sum II
Description
Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
may only be used once in the combination.
Note
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example
Code
- java
class Solution {
private List<List<Integer>> result;
public void dfs(int[] candidates, int index, LinkedList list, int sum, int target) {
if(sum == target) {
result.add(new LinkedList<Integer>(list));
return;
}
for(int i = index; i < candidates.length; i++) {
if(i > index && candidates[i] == candidates[i-1]) continue;
if(sum + candidates[i] <= target) {
list.add(candidates[i]);
dfs(candidates, i+1, list, sum+candidates[i], target);
list.removeLast();
}
}
}
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
LinkedList list = new LinkedList<Integer>();
result = new LinkedList<List<Integer>>();
Arrays.sort(candidates);
dfs(candidates, 0, list, 0, target);
return result;
}
}
Conclusion
- 上题的变型
- 需要排序,有重复的数
- 学习大佬的物理去重方法