以下为原题:
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.以target<=0为基准:若target<0,return;若target=0,add,return。
2.每一层递归都遍历给定的数组,遍历的起始位置是上一层递归正在遍历的位置。如果target>0,则在下一层递归中target减去当前递归层正被遍历的元素。
代码如下:
public List<List<Integer>> combinationSum(int[] candidates, int target) { if(candidates==null||candidates.length==0) return new ArrayList<>(); List<List<Integer>> allRes = new ArrayList<>(); combinationSumDetail(candidates,target,new ArrayList<>(),allRes,0); return allRes; } private void combinationSumDetail(int[] candidates, int target, List<Integer> subRes, List<List<Integer>> allRes, int start){ if(target<0) return; if(target==0){ allRes.add(new ArrayList<>(subRes)); return; } for(int i=start;i<candidates.length;++i){ subRes.add(candidates[i]); combinationSumDetail(candidates,target-candidates[i],subRes,allRes,i); subRes.remove(subRes.size()-1); } }