Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e1e22ed

Browse files
0040 组合总和II
简化原来的代码逻辑, 提高可读性。
1 parent e601c0c commit e1e22ed

File tree

1 file changed

+36
-31
lines changed

1 file changed

+36
-31
lines changed

‎problems/0040.组合总和II.md‎

Lines changed: 36 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -258,40 +258,45 @@ public:
258258
**使用标记数组**
259259
```Java
260260
class Solution {
261-
List<List<Integer>> lists = new ArrayList<>();
262-
Deque<Integer> deque = new LinkedList<>();
263-
int sum = 0;
264-
265-
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
266-
//为了将重复的数字都放到一起,所以先进行排序
267-
Arrays.sort(candidates);
268-
//加标志数组,用来辅助判断同层节点是否已经遍历
269-
boolean[] flag = new boolean[candidates.length];
270-
backTracking(candidates, target, 0, flag);
271-
return lists;
272-
}
261+
LinkedList<Integer> path = new LinkedList<>();
262+
List<List<Integer>> ans = new ArrayList<>();
263+
boolean[] used;
264+
int sum = 0;
273265

274-
public void backTracking(int[] arr, int target, int index, boolean[] flag) {
275-
if (sum == target) {
276-
lists.add(new ArrayList(deque));
277-
return;
278-
}
279-
for (int i = index; i < arr.length && arr[i] + sum <= target; i++) {
280-
//出现重复节点,同层的第一个节点已经被访问过,所以直接跳过
281-
if (i > 0 && arr[i] == arr[i - 1] && !flag[i - 1]) {
282-
continue;
283-
}
284-
flag[i] = true;
285-
sum += arr[i];
286-
deque.push(arr[i]);
287-
//每个节点仅能选择一次,所以从下一位开始
288-
backTracking(arr, target, i + 1, flag);
289-
int temp = deque.pop();
290-
flag[i] = false;
291-
sum -= temp;
292-
}
266+
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
267+
used = new boolean[candidates.length];
268+
// 加标志数组,用来辅助判断同层节点是否已经遍历
269+
Arrays.fill(used, false);
270+
// 为了将重复的数字都放到一起,所以先进行排序
271+
Arrays.sort(candidates);
272+
backTracking(candidates, target, 0);
273+
return ans;
274+
}
275+
276+
private void backTracking(int[] candidates, int target, int startIndex) {
277+
if (sum == target) {
278+
ans.add(new ArrayList(path));
279+
}
280+
for (int i = startIndex; i < candidates.length; i++) {
281+
if (sum + candidates[i] > target) {
282+
break;
283+
}
284+
// 出现重复节点,同层的第一个节点已经被访问过,所以直接跳过
285+
if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) {
286+
continue;
287+
}
288+
used[i] = true;
289+
sum += candidates[i];
290+
path.add(candidates[i]);
291+
// 每个节点仅能选择一次,所以从下一位开始
292+
backTracking(candidates, target, i + 1);
293+
used[i] = false;
294+
sum -= candidates[i];
295+
path.removeLast();
293296
}
297+
}
294298
}
299+
295300
```
296301
**不使用标记数组**
297302
```Java

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /