LeetCode: Combination Sum II 解题报告

时间:2022-06-14 03:16:36

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]

LeetCode: Combination Sum II 解题报告

SOLUTION 1:

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

 public List<List<Integer>> combinationSum2(int[] num, int target) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
if (num == null || num.length == 0) {
return ret;
} Arrays.sort(num); dfs(num, target, new ArrayList<Integer>(), ret, 0);
return ret;
} public void dfs1(int[] num, int target, ArrayList<Integer> path, List<List<Integer>> ret, int index) {
if (target == 0) {
ret.add(new ArrayList<Integer>(path));
return;
} if (target < 0) {
return;
} // 注意,这里从 i = index开始
// 每次只取第一个,例如 123334,到了333这里,我们第一次只取第1个3,因为我们选任何一个3是对组合来说是一个解。所以只
// 第一次取就好了。
int pre = -1;
for (int i = index; i < num.length; i++) {
int n = num[i];
if (n == pre) {
continue;
}
pre = n;
path.add(n);
dfs(num, target - n, path, ret, i + 1);
path.remove(path.size() - 1);
}
}

SOLUTION 2:

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

 public void dfs(int[] num, int target, ArrayList<Integer> path, List<List<Integer>> ret, int index) {
if (target == 0) {
ret.add(new ArrayList<Integer>(path));
return;
} if (target < 0) {
return;
} // 注意,这里从 i = index开始
// 每次只取第一个,例如 123334,到了333这里,我们第一次只取第1个3,因为我们选任何一个3是对组合来说是一个解。所以只
// 第一次取就好了。
for (int i = index; i < num.length; i++) {
int n = num[i];
if (i != index && n == num[i - 1]) {
continue;
}
path.add(n);
dfs(num, target - n, path, ret, i + 1);
path.remove(path.size() - 1);
}
}

GITHUB:

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