Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from Cunlimited number of times.
java
public class Solution {
/*
* @param candidates: A list of integers
* @param target: An integer
* @return: A list of lists of integers
*/
public List<List<Integer>> combinationSum(int[] candidates, int target) {
// write your code here
List<List<Integer>> result = new ArrayList<>();
if (candidates == null || candidates.length == 0) {
return result;
}
int[] candidate = removeDuplicate(candidates);
dfs(candidate, target, 0, new ArrayList<Integer>(), result);
return result;
}
private int[] removeDuplicate(int[] candidates) {
Arrays.sort(candidates);
int index = 0;
for (int i = 0; i < candidates.length; i++) {
if (candidates[index] != candidates[i]) {
candidates[++index] = candidates[i];
}
}
int[] arr = new int[index + 1];
for (int i = 0; i < index + 1; i++) {
arr[i] = candidates[i];
}
return arr;
}
private void dfs(int[] candidates,
int target,
int startIndex,
List<Integer> list,
List<List<Integer>> result) {
if (target < 0) {
return;
}
if (target == 0) {
result.add(new ArrayList<>(list));
return;
}
for (int i = startIndex; i < candidates.length; i++) {
list.add(candidates[i]);
dfs(candidates, target - candidates[i], i, list, result);
list.remove(list.size() - 1);
}
}
}
python
class Solution:
"""
@param: candidates: A list of integers
@param: target: An integer
@return: A list of lists of integers
"""
def combinationSum(self, candidates, target):
# write your code here
if candidates is None or len(candidates) == 0:
return []
candidates = self.removeDuplicate(candidates)
result = []
self.dfs(candidates, target, 0, [], result)
return result
def removeDuplicate(self, candidates):
candidates.sort()
index = 0
for i in range(len(candidates)):
if candidates[index] != candidates[i]:
index += 1
candidates[index] = candidates[i]
return candidates[: index + 1]
def dfs(self, candidates, target, startIndex, arr, result):
if target < 0:
return
if target == 0:
result.append(list(arr))
for i in range(startIndex, len(candidates)):
arr.append(candidates[i])
self.dfs(candidates, target - candidates[i], i, arr, result)
arr.pop()