leetcode 40. Combination Sum II
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:
public class Solution { public List<List<Integer>> combinationSum2(int[] candidates, int target) { List<List<Integer>> res = new ArrayList<List<Integer>>(); List<Integer> list = new ArrayList<Integer>(); Arrays.sort(candidates); combination(candidates,target,res,list,0); return res; } public void combination(int[] candidates,int target,List<List<Integer>> res,List<Integer> list,int index){ for(int i=index;i<candidates.length;i++){ if(candidates[i] == target){ List<Integer> tmp = new ArrayList<Integer>(list); //或tmp.addAll(list); tmp.add(candidates[i]); if(!res.contains(tmp)){ res.add(tmp); } }else if(candidates[i] < target){ List<Integer> tmp = new ArrayList<Integer>(list); //不能直接list.add(candidates[i]),然后将list向下传递 tmp.add(candidates[i]); combination(candidates,target-candidates[i],res,tmp,i+1); }else{ break; } } }
解法2:
leetcode上未通过,超时
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
Arrays.sort(candidates);
for(int i=1;i<=candidates.length;i++){
combine(candidates,0,list,res,i,target);
}
return res;
}
public void combine(int []cs,int begin,List<Integer> list,List<List<Integer>> res,int num,int target){
if(num == 0){
List<Integer> tmp = new ArrayList<Integer>(list);
if(target == 0 && !res.contains(tmp)){ //不能通过res.contains(list)判断元素是否重复,因为list的地址是不变的,判断一直为真
res.add(tmp); //不能res.add(list),list地址是不变的,且初始list为空,这样做的结果是 res最终也为空
}
return;
}
if(begin == cs.length) return;
list.add(cs[begin]);
combine(cs,begin+1,list,res,num-1,target-cs[begin]);
list.remove(list.size() -1);
combine(cs,begin+1,list,res,num,target);
}