题目原型:
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:
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,1,6]是把数组中的两个1都拿出来了,并不是一个1用了两次。清楚了这点后我们有两种方式,第一种是在上一题的代码上稍做改动后用set存结果。(比较耗时耗空间)至于两个内容相同的list对象能不能同时加入set中?我们等会再验证。第二种就是在上一题的基础上增加一个判断,保证两个连续相同的值不能重复计算。程序中有具体解释。
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); public ArrayList<ArrayList<Integer>> combinationSum2(int[] candidates, int target) { // 边界处理 if (candidates == null || candidates.length == 0) return list; if (target < 0) return list; // 对数组进行排序 Arrays.sort(candidates); combinationSum(candidates, target, new ArrayList<Integer>(), 0); return list; } public void combinationSum(int[] candidates, int target, ArrayList<Integer> num, int startIndex) { if (target < 0) return; // 如果目标数为0则假如目标list if (target == 0) { list.add(new ArrayList<Integer>(num)); return; } for (int i = startIndex; i < candidates.length; i++) { num.add(candidates[i]); combinationSum(candidates, target - candidates[i], num, i + 1); num.remove(num.size() - 1);// 注意加进去之后要回收,否则会影响下面的操作 //要找到两个连续的不同元素,因为一旦相同,某个数num后面的相同的元素能处理的情况num也能处理 //如:{1,[1],2,2} target=3 //3=1+2和3=[1]+2.既然3已经根据1+2求出了,那么就不必再求重复的[1]+2 while(i < candidates.length-1&&candidates[i]==candidates[i+1]) i++; } }
在上面我们说到,两个具有相同元素的list对象是否能同时加入到set中,验证如下:
public static void main(String[] args) { Set<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>(); ArrayList<Integer> list1 = new ArrayList<Integer>(); ArrayList<Integer> list2 = new ArrayList<Integer>(); list1.add(1); list1.add(198); list2.add(1); list2.add(198); System.out.println(list1.hashCode()==list2.hashCode());//true //猜测,在计算hashCode时,可能是把list中每个元素的hashCode值相加了,然后再比较两个list的hashCode值。 //由于hashCode()是个本地方法,源码看不到,所以有待验证。 set.add(list1); set.add(list2); System.out.println(set.size());//结果是1 }
Combination Sum II,布布扣,bubuko.com
原文:http://blog.csdn.net/cow__sky/article/details/22187703