原题:
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.
- 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] ]
思考过程:任然是递归思想,,但与Combination Sum Ⅰ不同的是,每次向下递归,都从i+1开始,而不是i,因为这次每个元素只能用一次。而且为了防止重复,一个元素如果用过了,以后和它数值相同的元素不可以再用。一开始我觉得不用排序,用哈希表限制元素不重复使用,结果出了问题。简单的比如{1,5,1},target = 6这种,虽然后面的1不会再单独递归,但遍历到5的时候会有[5,1]这种答案。所以不仅相同元素不再递归,而且相同元素之间不可以有其它元素,否则会重复利用。
解题思路:
看代码和注释吧。
结果代码:
public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates);//排序 return recursive(candidates,0,target); } public List<List<Integer>> recursive(int[] candidates,int begin,int target){ List<List<Integer>> res = new ArrayList<>(); for (int i = begin;i < candidates.length;i++){ if (i > begin && candidates[i] == candidates[i - 1]) continue;//注意判断i > begin,一开始只为了防止数组越界,写的 i > 0,结果连续相同的元素就不能用第二次。像{1,1,3},target = 5这种,就没有结果 if (candidates[i] > target) return res;//一开始没这个语句,显示超时,加上居然就不超时了,个人觉得差不多省了一半时间,但效果显著 if (candidates[i] == target) {//找到结果,添加到结果集 List<Integer> list = new ArrayList<>(); list.add(candidates[i]);res.add(list); } List<List<Integer>> lists = recursive(candidates,i + 1,target - candidates[i]); for (int j = 0;j < lists.size();j++){//结合下面递归的结果,处理结果集 lists.get(j).add(candidates[i]); res.add(lists.get(j)); } } return res; }