Leetcode40--->Combination Sum II

题目: 给定一个数组candidate和一个目标值target,求出candidate中所有和等于target的组合;

数组中的同一位的数字只能使用一次;

举例:

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]
]
解题思路:
该题与Leetcode39的解法是一样的,只是在细节处理上稍微有点差别。
代码如下:
 1 public class Solution {
 2     public List<List<Integer>> combinationSum2(int[] candidates, int target) {
 3 
 4         List<List<Integer>> LList = null;
 5         if(candidates == null || candidates.length < 1)
 6             return LList;
 7         Arrays.sort(candidates);
 8         List<Integer> list = new ArrayList<Integer>();
 9         Set<List<Integer>> set = new HashSet<List<Integer>>();  // 这里我将Leetcode39中的List,改为了set,其实是一样的,因为之前对数组排过序了
10         combinationCore(candidates, 0, target, list, set);
11         LList = new ArrayList<>(set);
12         return LList;
13     }
14     public void combinationCore(int[] candidates, int index, int target, List<Integer> list, Set<List<Integer>> set){
15         for(int i = index; i < candidates.length; i++){
16             if(target == candidates[i]){
17                 List<Integer> res = new ArrayList<Integer>();
18                 res.addAll(list);
19                 res.add(candidates[i]);
20                 set.add(res);
21             }
22             else if(target > candidates[i]){
23                 List<Integer> res = new ArrayList<Integer>();
24                 res.addAll(list);
25                 res.add(candidates[i]);
26                 combinationCore(candidates, i + 1, target - candidates[i], res, set);  // 注意这里是i + 1,这是与Leetcode39不同的地方
27             }
28             else
29                 break;
30         }
31     }
32 }
原文地址:https://www.cnblogs.com/leavescy/p/5901338.html