Saturday, January 25, 2014

Combination Sum II (Java)

LeetCode


Given a collection of candidate numbers (C) and a target number (T), 
find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5 and target 8
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6] 

Solution: DFS
     Apply DFS continually check every combination, if any one meet the target put it into result arraylist.
/*Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
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 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
*/
public class CombinationSumII {
public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();
if (num==null||num.length==0){
return result;
}
ArrayList<Integer> current=new ArrayList<Integer>();
int start=0;
Arrays.sort(num);
buildResult(num,start, target, current, result);
return result;
}
private void buildResult(int[] num, int start, int target, ArrayList<Integer> current, ArrayList<ArrayList<Integer>> result){
if (target==0){
ArrayList<Integer> temp=new ArrayList<Integer>(current);
result.add(temp);
return;
}
for (int i=start; i<num.length; i++){
if (num[i]>target){
continue;
}
current.add(num[i]);
buildResult(num,i+1, target-num[i], current,result);
current.remove(current.size()-1);
while(i+1<num.length && num[i]==num[i+1]){
i++;
}
}
}
}

No comments:

Post a Comment