题目
结果
代码
超时的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Solution { private final List<List<Integer>> ans = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) { List<Integer> candidateList = new LinkedList<>();
for (int num : candidates) { candidateList.add(num); } search(candidateList, target, new LinkedList<>()); ans.forEach(integers -> integers.sort(Integer::compareTo)); return ans.stream().distinct().collect(Collectors.toList()); }
private void search(List<Integer> candidates, int target, List<Integer> tmp) { if (target < 0) { return; } if (target == 0) { ans.add(new LinkedList<>(tmp)); } for (int num : candidates) { List<Integer> newTmp = new LinkedList<>(tmp); newTmp.add(num); List<Integer> newCandidates = new LinkedList<>(candidates); newCandidates.remove((Object) num); search(newCandidates, target - num, newTmp); } } }
|
上面的代码会超时,主要是因为在复制list的过程中消耗了过多的时间,可以改进一下,于是有了第二种算法。
飘过的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| class Solution { private final List<List<Integer>> ans = new LinkedList<>(); private boolean[] flag;
public List<List<Integer>> combinationSum2(int[] candidates, int target) { flag = new boolean[candidates.length];
List<Integer> candidateList = new LinkedList<>(); for (int num : candidates) { candidateList.add(num); } search(candidateList, target, new LinkedList<>()); ans.forEach(integers -> integers.sort(Integer::compareTo)); return ans.stream().distinct().collect(Collectors.toList()); }
private void search(List<Integer> candidates, int target, List<Integer> tmp) { if (target < 0) { return; } if (target == 0) { ans.add(new LinkedList<>(tmp)); }
for (int i = 0; i < candidates.size(); i++) { if (flag[i]) { continue; } List<Integer> newTmp = new LinkedList<>(tmp); newTmp.add(candidates.get(i)); flag[i] = true; search(candidates, target - candidates.get(i), newTmp); flag[i] = false; } } }
|