This commit is contained in:
fanxb 2022-01-04 23:21:29 +08:00
parent 80317a8214
commit f630b021d0

View File

@ -1,5 +1,6 @@
package com.fanxb.common; package com.fanxb.common;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
@ -12,26 +13,31 @@ public class Q40 {
return res; return res;
} }
private void deal(List<List<Integer>> res, List<Integer> cur, int i, int[] sources, int target) { private void deal(List<List<Integer>> res, List<Integer> cur, int start, int[] sources, int target) {
if (target < sources[i]) { if (start >= sources.length || target < sources[start]) {
return; return;
} }
for (; i < sources.length; i++) { for (int i = start; i < sources.length; i++) {
if (sources[i] > target) { if (sources[i] > target) {
return; return;
} }
List<Integer> temp = new LinkedList<>(cur); if (i > start && sources[i] == sources[i - 1]) {
temp.add(sources[i]); //第二个重复的元素不需要进行后续操作
if (sources[i] == target) { continue;
res.add(temp);
} else {
deal(res, temp, i + 1, sources, target - sources[i]);
} }
cur.add(sources[i]);
if (sources[i] == target) {
res.add(new ArrayList<>(cur));
} else {
deal(res, cur, i + 1, sources, target - sources[i]);
}
//加入后删除当前元素尝试下一个
cur.remove(cur.size() - 1);
} }
} }
public static void main(String[] args) { public static void main(String[] args) {
new Q40().combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8); new Q40().combinationSum2(new int[]{2, 5, 2, 1, 2}, 5);
} }