add
This commit is contained in:
parent
80317a8214
commit
f630b021d0
@ -1,5 +1,6 @@
|
||||
package com.fanxb.common;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
@ -12,26 +13,31 @@ public class Q40 {
|
||||
return res;
|
||||
}
|
||||
|
||||
private void deal(List<List<Integer>> res, List<Integer> cur, int i, int[] sources, int target) {
|
||||
if (target < sources[i]) {
|
||||
private void deal(List<List<Integer>> res, List<Integer> cur, int start, int[] sources, int target) {
|
||||
if (start >= sources.length || target < sources[start]) {
|
||||
return;
|
||||
}
|
||||
for (; i < sources.length; i++) {
|
||||
for (int i = start; i < sources.length; i++) {
|
||||
if (sources[i] > target) {
|
||||
return;
|
||||
}
|
||||
List<Integer> temp = new LinkedList<>(cur);
|
||||
temp.add(sources[i]);
|
||||
if (sources[i] == target) {
|
||||
res.add(temp);
|
||||
} else {
|
||||
deal(res, temp, i + 1, sources, target - sources[i]);
|
||||
if (i > start && sources[i] == sources[i - 1]) {
|
||||
//第二个重复的元素不需要进行后续操作
|
||||
continue;
|
||||
}
|
||||
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) {
|
||||
new Q40().combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8);
|
||||
new Q40().combinationSum2(new int[]{2, 5, 2, 1, 2}, 5);
|
||||
}
|
||||
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user