Given a set of candidate numbers (C) (without duplicates) 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.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]
一刷没ac
解题思路:回溯法。留坑做专题整理。
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> rst = new ArrayList<List<Integer>>();
List<Integer> res = new ArrayList<Integer>();
Arrays.sort(candidates);
backtrace(rst, res, candidates, target, 0);
return rst;
}
public void backtrace(List<List<Integer>> rst, List<Integer> res, int[] candidates, int remain, int start){
if(remain < 0) return;
if(remain == 0) rst.add(new ArrayList<>(res));
for(int i = start; i < candidates.length; i++){
res.add(candidates[i]);
backtrace(rst, res, candidates, remain-candidates[i], i);
res.remove(res.size()-1);
}
}
}