题目: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.
题意:给一个数组,判断数组里的数能不能相加得到目标数T,数组里的每个数可以使用多次
思路: 比较简单的dfs吧, 对每个数都"尝试"加一下,然后去掉这个数,递归寻解
import java.util.*;
public class Solution {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
void dfs(int[] a,int sum,int k,int cur) {//sum : 当前和 k: 目标和
if(sum>=k) {
if(sum==k){
ans.add(new ArrayList(list));
}
return;
}
for (int i = cur; i < a.length; i++) {
list.add(a[i]);
dfs(a,a[i]+sum,k,i);//因为每个数可以使用多次所以第4个参数仍是i
list.remove(list.size()-1);
}
}
public List<List<Integer>> combinationSum(int[] c, int t) {
dfs(c,0,t,0);
return ans;
}
}