40.Combination Sum II

题目链接:https://leetcode.com/problems/combination-sum-ii/description/

题目大意:与39题类似,只是这里数组中的数字可以有重复,且每一个数字只能取一次。

法一:利用39题的剪枝代码,加了一个去重的操作(与前面47和90的去重操作一样)。代码如下(耗时27ms):

 1     public List<List<Integer>> combinationSum2(int[] candidates, int target) {
 2         List<List<Integer>> res = new ArrayList<List<Integer>>();
 3         List<Integer> tmp = new ArrayList<Integer>();
 4         Arrays.sort(candidates);//先进行排序
 5         dfs(res, tmp, candidates, target, 0);
 6         return res;
 7     }
 8     public static boolean dfs(List<List<Integer>> res, List<Integer> tmp, int[] candidates, int target, int start) {
 9         if(target < 0) {
10             return false;
11         }
12         if(target == 0) {//递归结束条件
13             res.add(new ArrayList<Integer>(tmp));
14             return false;
15         }
16         else {//这里一定要判断target>0,因为如果不判断就会导致target<0时还在往下递归
17             for(int i = start; i < candidates.length; i++) {
18                 //去重
19                 if(i > start && candidates[i] == candidates[i - 1]) {
20                     continue;
21                 }
22                 tmp.add(candidates[i]);
23                 boolean flag = dfs(res, tmp, candidates, target - candidates[i], i + 1);//这里是i,因为不能重复选
24                 tmp.remove(tmp.size() - 1);
25                 //剪枝,因为数组是排好序的,所以一旦总和<=0,那么其后的数字一定会导致当前结果<0,所以可以直接从此跳过后面的循环
26                 if(flag == false) {
27                     break;
28                 }
29             }
30         }
31         return true;
32     }
View Code
原文地址:https://www.cnblogs.com/cing/p/7883233.html