Given a set of candidate numbers (candidates) (without duplicates) and
a target number (target), find all unique combinations in candidates
where the candidate numbers sums to target.The same repeated number may be chosen from candidates unlimited
number of times.Note:
All numbers (including target) will be positive integers. The solution
set must not contain duplicate combinations.
Example 1:Input: candidates = [2,3,6,7], target = 7, A solution set is: [ [7],
[2,2,3] ]
Example 2:Input: candidates = [2,3,5], target = 8, A solution set is: [
[2,2,2,2], [2,3,3], [3,5] ]
根据数组中的字数,求取加和为目标数,数组中数字出现次数可大于1.
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
return combinationSum1(candidates, target, 0);
}
public List<List<Integer>> combinationSum1(int[] candidates, int target, int begin) {
int n =candidates.length;
List<List<Integer>> ret = new ArrayList();
for(int i = begin; i < n; i++){
int num = candidates[i];
int c = target / num;
if(c == 0) {
return ret;
}
for (int s = 1; s < c + 1; s++) {
List<List<Integer>> temp = combinationSum1(candidates, target - num * s, 1 + i);
if(temp.size() > 0) {
for(int j = 0 ;j < temp.size(); j++) {
List<Integer> com = temp.get(j);
for(int k = 1; k < s + 1; k++) {
com.add(num);
}
ret.add(com);
}
} else if(num * s == target){
List<Integer> com = new ArrayList();
for(int k = 1; k < s + 1; k++) {
com.add(num);
}
ret.add(com);
}
}
}
return ret;
}
}