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 C unlimited number of times.
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) {
List<List<Integer>> results = new ArrayList<>();
List<Integer> result = new ArrayList<>();
Set<List<Integer>> hash = new HashSet<>();
if (candidates == null || candidates.length == 0) {
return results;
}
Arrays.sort(candidates);
dfsHelper(candidates, 0, target, 0, results,result, hash);
return results;
}
//使用hashset去重
private void dfsHelper(int[] candidates,
int sum,
int target,
int index,
List<List<Integer>> results,
List<Integer> result,
Set<List<Integer>> hash) {
if (index > candidates.length ) {
return;
}
if (sum == target) {
ArrayList<Integer> temp = new ArrayList(result);
if (!hash.contains(temp)) {
results.add(temp);
hash.add(temp);
}
}
for (int i = index; i < candidates.length; i++) {
//由于是排序数组,如果sum + candidates已经超过target,则不用往下搜索
if (sum + candidates[i] > target) {
break;
}
sum += candidates[i];
result.add(candidates[i]);
dfsHelper(candidates, sum, target, i, results, result, hash);
sum -= result.get(result.size() - 1);
result.remove(result.size() - 1);
}
}
}