题目:
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]
思路:
这种组合题目,首先想到递归方法。每次找准一个,往下一层递归就好了。
在思路上没有任何难度。但是有一些注意事项:
1,首先如例子所述,组成8 的不一定是1,7,还有7,1。这两个1虽然不是同一个元素1,但是
题目也是不允许的。因此,我们想到了set,其中不能有重复元素,但是set对于list来说如何判重呢?
转而想到使用list.contain()方法去比较是否有两个元素一模一样的list。
但是,若list1={1,7},list2={7,1},则list.contain()中是对这两个区别对待的。因此,需要在顺序上做一定排列。
即,两个list的比较中,不光是元素一样,元素的位置也必须一样。
所以,在递归寻找之前,先把candidate数组排序(利用Arrays.sort),这时出来的list1和list2就都是{1,7}了。
这样才能实现真正的去重。
AC代码:
public class Combination_Sum_II {
private LinkedList<Integer> list = new LinkedList<Integer>();
private LinkedList<List<Integer>> rst = new LinkedList<List<Integer>>();
private void combine(int[] num, int begin, int target, int sum) {
if (begin >= num.length) {
if (sum == target)
rst.add(new LinkedList<Integer>(list));
} else {
for (int i = begin; i < num.length; i++) {
if (sum + num[i] < target) {
list.add(num[i]);
combine(num, i + 1, target, sum + num[i]);
list.removeLast();
} else if (sum + num[i] == target) {
list.add(num[i]);
if (!rst.contains(list))
rst.add((List<Integer>) list.clone());
list.removeLast();
}
}
}
}
public List<List<Integer>> combinationSum2(int[] num, int target) {
Arrays.sort(num);
combine(num, 0, target, 0);
return rst;
}
public static void main(String[] args) {
Combination_Sum_II combination_sum_ii = new Combination_Sum_II();
int[] num = {10,1,2,7,6,1,5};
int target = 1;
List<List<Integer>> list = combination_sum_ii.combinationSum2(num, target);
for (List lis : list) {
for (Object integer : lis) {
System.out.print(" " + integer);
}
System.out.println();
}
}
}