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.
For example, given candidate set
A solution set is:
Have you met this question in a real interview? 2,3,6,7
and target 7
, A solution set is:
[7]
[2, 2, 3]
Yes
Example
given candidate set
A solution set is:
2,3,6,7
and target 7
, A solution set is:
[7]
[2, 2, 3]
Note
public class Solution {- All numbers (including target) will be positive integers.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- The solution set must not contain duplicate combinations.
/**
* @param candidates: A list of integers
* @param target:An integer
* @return: A list of lists of integers
*/
public List<List<Integer>> combinationSum(int[] candidates, int target) {
// write your code here
List<List<Integer>> res = new ArrayList<List<Integer>>();
Arrays.sort(candidates);
combinationSum(res, 0, candidates, new ArrayList<Integer>(), target);
return res;
}
private void combinationSum(List<List<Integer>> res, int start, int[] candidates, List<Integer> sub, int target){
if(target == 0){
res.add(new ArrayList<Integer>(sub));
return;
}
for(int i = start; i < candidates.length; i++){
if(i > 0 && candidates[i] == candidates[i-1]) continue;
if(candidates[i] <= target){
sub.add(candidates[i]);
combinationSum(res, i, candidates, sub, target-candidates[i]);
sub.remove(sub.size()-1);
}
}
}
}
No comments:
Post a Comment