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
A solution set is:
DFS问题,主要注意两个问题:10,1,2,7,6,1,5 and target 8,A solution set is:
[1, 7][1, 2, 5][2, 6][1, 1, 6] - 在DFS的时候去除重复情况
- 及时的停止DFS来减少时间,否则对于大输入会TLE
但是这种写法不是太优雅,另外一种用循环来枚举子问题的方法更加优雅。
public class Solution {
public List<List<Integer>> combinationSum2(int[] num, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> current = new ArrayList<Integer>();
if(num.length == 0) return result; // invalid input
Arrays.sort(num);
dfs(num, target, 0, 0, current, result);
return result;
}
private void dfs(int[] num, int target, int sum, int ind, List<Integer> current, List<List<Integer>> result) {
if(ind == num.length) return;
if(sum > target) return;
current.add(num[ind]);
if(sum + num[ind] == target) result.add(new ArrayList<Integer>(current));
dfs(num, target, sum+num[ind], ind + 1, current, result);
current.remove(current.size() - 1);
int i = ind;
while(i < num.length && num[i] == num[ind]) i++; // skip duplicate
dfs(num, target, sum, i, current, result);
}
}
private void dfs(int[] num, int sum, int ind, List<Integer> current, List<List<Integer>> result) {
if(sum < 0) return;
else if(sum == 0) {
result.add(new ArrayList<Integer>(current));
}
else {
for(int i = ind; i < num.length; i++) {
if(i > ind && num[i] == num[i-1]) continue;
current.add(num[i]);
dfs(num, sum-num[i], i+1, current, result);
current.remove(current.size() - 1);
}
}
}
没有评论:
发表评论