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.
Note:
- 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.
For example, given candidate set 2,3,6,7
and target 7
,
A solution set is:
[7]
[2, 2, 3]
=============
Analysis:
Similar approach as the "subsets" problems. Idea of which is to recursively adding the current element, if the target reached, than add this array list to the result set. After each recursive call, remove the previous added element, and try the next element for the current level.
public class Solution {
public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
ArrayList<ArrayList<Integer>> rs = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> temp = new ArrayList<Integer>();
Arrays.sort(candidates);
helper(candidates, target, rs, temp, 0);
return rs;
}
public void helper(int[] candidates, int target, ArrayList<ArrayList<Integer>> rs, ArrayList<Integer> temp, int index){
if(target == 0){
if(!rs.contains(temp)) rs.add(new ArrayList<Integer>(temp));
}
else{
for(int i=index; i<candidates.length;i++){
if(target-candidates[i]>=0) {
temp.add(candidates[i]);
helper(candidates, target-candidates[i], rs, temp, i);
temp.remove(temp.size()-1);
}
}
}
}
}