题目传送地址: https://leetcode.cn/problems/combination-sum-ii/

代码如下:
public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
Set<String> set = new HashSet<>();
//先排序
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < candidates.length; i++) {
if (candidates[i] > target) {
continue;
}
List<List<Integer>> combination = combination(candidates, i, target);
if (!combination.isEmpty()) {
for (List<Integer> list : combination) {
if (set.add(Arrays.toString(list.toArray()))) {
result.add(list);
}
}
}
}
return result;
}
//以索引位置i处的元素结尾,且组合出来的结果=target
public static List<List<Integer>> combination(int[] candidates, int i, int target) {
List<List<Integer>> result = new ArrayList<>();
if (target == 0) {
result.add(Arrays.asList());
return result;
}
if (target == candidates[i]) {
result.add(Arrays.asList(target));
return result;
}
if (target - candidates[i] < 0) { //
return result;
}
int lastIndex = i - 1;
if (lastIndex == 0 && candidates[0] == target - candidates[i]) {
result.add(Arrays.asList(candidates[0], candidates[1]));
return result;
}
int repeatCount = 1;
while (lastIndex > 0 && candidates[lastIndex] == candidates[i]) {
lastIndex--;
repeatCount++;
}
for (int m = 1; m <= repeatCount; m++) {
int n = lastIndex;
while (n >= 0) {
List<List<Integer>> combination = combination(candidates, n, target - m * candidates[i]);
for (List<Integer> list : combination) {
List<Integer> integers = new ArrayList<>(list);
for (int j = 0; j < m; j++) {
integers.add(candidates[i]);
}
result.add(integers);
}
n--;
}
}
return result;
}
















