思路:
数组内的每一个元素都可以无线使用只要最后可以拼接成target就可以。那么如何限制呢?
(target-已经拼接的和 )/当前元素 就是你可以利用的数量。代码如下:
class Solution {
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans=new ArrayList<>();
if (candidates==null||candidates.length==0){
return ans;
}
Deque<Integer> path=new LinkedList<>();
process(candidates,0,target,path,ans);
return ans;
}
private static void process(int[] candidates, int index, int rest, Deque<Integer> path, List<List<Integer>> ans) {
if (rest==0){
ans.add(new ArrayList<>(path));
return;
}
if (index==candidates.length){
return;
}
int count=rest/candidates[index];
for (int i = 0; i <=count; i++) {
if (i!=0){
path.addFirst(candidates[index]);
}
process(candidates,index+1,rest-candidates[index]*i,path,ans);
}
//移除path张数
for (int i = 1; i <=count; i++) {
path.removeFirst();
}
}
}
这里使用的双端队列,目的就是为了方便还原现场