Combination Sum II 153
Question
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.
Notice
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.
Example
Given candidate set [10,1,6,7,2,1,5] and target 8,
A solution set is:
[ [1,7],
[1,2,5],
[2,6],
[1,1,6] ]
Solution
与Combination Sum类似。但是因为每个数只能用一次,下一层pos为上一层pos+1。避免重复的方法:重复的数只能取第一个元素。
代码如下:
需要额外O(n)空间记录元素状态
public class Solution {
/**
* @param num: Given the candidate numbers
* @param target: Given the target number
* @return: All the combinations that sum to target
*/
public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
// write your code here
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(num == null || num.length == 0 || target <= 0){
return result;
}
ArrayList<Integer> list = new ArrayList<Integer>();
Arrays.sort(num);
int[] visit = new int[num.length];
helper(result, list, num, target, 0, visit);
return result;
}
private void helper(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> list, int[] num, int target, int pos, int[] visit){
if(target == 0){
result.add(new ArrayList<Integer>(list));
return;
}
for(int i = pos; i < num.length; i++){
if(visit[i] == 1 || (i != 0 && num[i] == num[i - 1] && visit[i - 1]== 0)){
continue;
}
if(num[i] > target){
return;
}
list.add(num[i]);
visit[i] = 1;
helper(result, list, num, target - num[i], i + 1, visit);
list.remove(list.size() - 1);
visit[i] = 0;
}
}
}
Revised version:
public class Solution {
private ArrayList<ArrayList<Integer>> results;
public ArrayList<ArrayList<Integer>> combinationSum2(int[] candidates,
int target) {
if (candidates.length < 1) {
return results;
}
ArrayList<Integer> path = new ArrayList<Integer>();
java.util.Arrays.sort(candidates);
results = new ArrayList<ArrayList<Integer>> ();
combinationSumHelper(path, candidates, target, 0);
return results;
}
private void combinationSumHelper(ArrayList<Integer> path, int[] candidates, int sum, int pos) {
if (sum == 0) {
results.add(new ArrayList<Integer>(path));
}
if (pos >= candidates.length || sum < 0) {
return;
}
int prev = -1;
for (int i = pos; i < candidates.length; i++) {
//重复的数只能取第一个元素
if (candidates[i] != prev) {
path.add(candidates[i]);
combinationSumHelper(path, candidates, sum - candidates[i], i + 1);
prev = candidates[i];
path.remove(path.size()-1);
}
}
}
}