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.
java
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
if (candidates == null || candidates.length == 0) {
return result;
}
Arrays.sort(candidates);
Set<List<Integer>> set = new HashSet<>();
dfs(candidates, target, 0, new ArrayList<Integer>(), set);
return new ArrayList<List<Integer>>(set);
}
private void dfs(int[] candidates,
int target,
int startIndex,
List<Integer> list,
Set<List<Integer>> set) {
if (target < 0) {
return;
}
if (target == 0) {
set.add(new ArrayList<Integer>(list));
}
for (int i = startIndex; i < candidates.length; i++) {
list.add(candidates[i]);
dfs(candidates, target - candidates[i], i + 1, list, set);
list.remove(list.size() - 1);
}
}
}
java
public class Solution {
/*
* @param num: Given the candidate numbers
* @param target: Given the target number
* @return: All the combinations that sum to target
*/
public List<List<Integer>> combinationSum2(int[] num, int target) {
// write your code here
List<List<Integer>> result = new ArrayList<>();
if (num == null || num.length == 0) {
return result;
}
Arrays.sort(num);
dfs(num, target, 0, new ArrayList<Integer>(), result);
return result;
}
private void dfs(int[] num,
int target,
int startIndex,
List<Integer> list,
List<List<Integer>> result) {
if (target < 0) {
return;
}
if (target == 0) {
result.add(new ArrayList<Integer>(list));
}
for (int i = startIndex; i < num.length; i++) {
if (i != startIndex && num[i] == num[i - 1]) {
continue;
}
list.add(num[i]);
dfs(num, target - num[i], i + 1, list, result);
list.remove(list.size() - 1);
}
}
}
python
class Solution:
"""
@param: num: Given the candidate numbers
@param: target: Given the target number
@return: All the combinations that sum to target
"""
def combinationSum2(self, num, target):
# write your code here
if num is None or len(num) == 0:
return []
result = []
num.sort()
self.dfs(num, target, 0, [], result)
return result
def dfs(self, num, target, startIndex, arr, result):
if target < 0:
return
if target == 0:
result.append(list(arr))
for i in range(startIndex, len(num)):
if i != startIndex and num[i] == num[i - 1]:
continue
arr.append(num[i])
self.dfs(num, target - num[i], i + 1, arr, result)
arr.pop()