题目链接:https://leetcode.com/problems/combination-sum-ii/
题目:
C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
C may only be used once
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.
10,1,2,7,6,1,5
and target 8
,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
思路:
candidate set每个元素只允许选择一次。因为set中可能会有重复的元素导致solution set中可能会有重复解,比如sum=8,candidate set[1,1,7],就有两个[1,7]解。每个元素只选择一次,可以在Combination Sum 中改为 dspCombination(sum, i+1);,为了解决重复解的问题,我们引入HashSet保存解,最后在将hashSet转为List返回就好了。
算法:
int cl[] = null;
List<List<Integer>> iLists = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
HashSet<ArrayList<Integer>> sets = new HashSet<ArrayList<Integer>>();
int target = 0;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
this.cl = candidates;
this.target = target;
dspCombination2(0, 0);
iLists.addAll(sets); //HashSet 转为 List
return iLists;
}
private void dspCombination2(int sum, int level) {
if (sum == target) {
sets.add(new ArrayList<Integer>(list)); //用HashSet保存解
return;
} else if (sum > target) {
return;
} else {
for (int i = level; i < cl.length; i++) {
sum += cl[i];
list.add(cl[i]);
dspCombination2(sum, i + 1); //每个元素只允许选择一次
list.remove(list.size() - 1);
sum -= cl[i];
}
}
}