39. Combination Sum (Medium) Uber Snapchat
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 target7
,
A solution set is:
[
[7],
[2, 2, 3]
]
Solution 1: DFS O(n * 2^n); O(n)
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
if (candidates == null || candidates.length == 0) {
return res;
}
Arrays.sort(candidates);
dfs(res, new ArrayList<>(), candidates, 0, target);
return res;
}
private void dfs(List<List<Integer>> res, List<Integer> comb, int[] candidates, int start, int remain) {
// if (remain < 0) {
// return;
// }
if (remain == 0) {
res.add(new ArrayList<>(comb));
}
for (int i = start; i < candidates.length; i++) {
if (candidates[i] > remain) {
break;
}
comb.add(candidates[i]);
dfs(res, comb, candidates, i, remain - candidates[i]); //数组无重复,每个数可用多次
comb.remove(comb.size() - 1);
}
}