40.Combination Sum II

題目連接:https://leetcode.com/problems/combination-sum-ii/description/數組

題目大意:與39題相似,只是這裏數組中的數字能夠有重複,且每個數字只能取一次。ide

法一:利用39題的剪枝代碼,加了一個去重的操做(與前面47和90的去重操做同樣)。代碼以下(耗時27ms):spa

 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
相關文章
相關標籤/搜索