39 Combination Sum
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Example 1:
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
Example 2:
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Example 3:
Input: candidates = [2], target = 1
Output: []
递归。从第一个数开始,尝试 0 次,1 次。。。然后第二个数做同样的尝试,直到超过目标。使用一个数组记录每个数用了多少次,以便生成 List 。
class Solution {
List<List<Integer>> ret;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
ret=new ArrayList<>();
ArrayList<Integer> list=new ArrayList<>();
Arrays.sort(candidates);
int[] count=new int[candidates.length];
recur(candidates, target, candidates.length-1, count);
return ret;
}
private void recur(int[] can, int target, int index, int[] count){
if(index<0) return;
int cur=can[index];
recur(can,target,index-1, count);
while(target>0){
target=target-cur;
count[index]++;
if(target==0) {
ret.add(toList(can,count));
} else {
recur(can,target,index-1,count);
}
}
count[index]=0;
}
private List<Integer> toList(int[] can, int[] count){
ArrayList<Integer> list=new ArrayList<>();
for(int i=0;i<can.length;++i){
for(int j=0;j<count[i];++j){
list.add(can[i]);
}
}
return list;
}
}
class Solution {
List<List<Integer>> ret;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
ret=new LinkedList<>();
int[] count=new int[candidates.length];
dp(candidates, target, 0, count);
return ret;
}
private void dp(int[] candidates, int remain, int index, int[] count){
if(remain==0){
ret.add(toList(candidates, count));
return;
}
if(index==candidates.length) return;
int num=candidates[index];
do{
dp(candidates, remain, index+1, count);
remain-=num;
count[index]+=1;
} while (remain>=0);
count[index]=0;
}
private List<Integer> toList(int[] candidates, int[] count){
List<Integer> list=new LinkedList<>();
for(int i=0;i<count.length;++i){
if(count[i]!=0){
for(int j=0;j<count[i];++j){
list.add(candidates[i]);
}
}
}
return list;
}
}