LeetCode: Combination Sum II 解题报告

Combination Sum II

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:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
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]

SOLUTION 1:

注意,这里从 i = index开始
每次只取第一个,例如 123334,到了333这里,我们第一次只取第1个3,因为我们选任何一个3是对组合来说是一个解。所以只第一次取就好了。

 1 public List<List<Integer>> combinationSum2(int[] num, int target) {
 2         List<List<Integer>> ret = new ArrayList<List<Integer>>();
 3         if (num == null || num.length == 0) {
 4             return ret;
 5         }
 6         
 7         Arrays.sort(num);
 8         
 9         dfs(num, target, new ArrayList<Integer>(), ret, 0);
10         return ret;
11     }
12     
13     public void dfs1(int[] num, int target, ArrayList<Integer> path, List<List<Integer>> ret, int index) {
14         if (target == 0) {
15             ret.add(new ArrayList<Integer>(path));
16             return;
17         }
18         
19         if (target < 0) {
20             return;
21         }
22         
23         // 注意,这里从 i = index开始
24         // 每次只取第一个,例如 123334,到了333这里,我们第一次只取第1个3,因为我们选任何一个3是对组合来说是一个解。所以只
25         // 第一次取就好了。
26         int pre = -1;
27         for (int i = index; i < num.length; i++) {
28             int n = num[i];
29             if (n == pre) {
30                 continue;
31             }
32             pre = n;
33             path.add(n);
34             dfs(num, target - n, path, ret, i + 1);
35             path.remove(path.size() - 1);
36         }
37     }
View Code

SOLUTION 2:

不使用pre来判断也可以,只要判断当前值是不是与上一个值相同,如果相同不取。我们只考虑i = index即可,因为这么多相同的值也只需要取一个

 1 public void dfs(int[] num, int target, ArrayList<Integer> path, List<List<Integer>> ret, int index) {
 2         if (target == 0) {
 3             ret.add(new ArrayList<Integer>(path));
 4             return;
 5         }
 6         
 7         if (target < 0) {
 8             return;
 9         }
10         
11         // 注意,这里从 i = index开始
12         // 每次只取第一个,例如 123334,到了333这里,我们第一次只取第1个3,因为我们选任何一个3是对组合来说是一个解。所以只
13         // 第一次取就好了。
14         for (int i = index; i < num.length; i++) {
15             int n = num[i];
16             if (i != index && n == num[i - 1]) {
17                 continue;
18             }
19             path.add(n);
20             dfs(num, target - n, path, ret, i + 1);
21             path.remove(path.size() - 1);
22         }
23     }
View Code

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/combination/CombinationSum2_1203.java

原文地址:https://www.cnblogs.com/yuzhangcmu/p/4141347.html