Skip to content

Commit 1244f1d

Browse files
Merge pull request youngyangyang04#876 from Younglesszzz/master
更新回溯的另一种写法 全排列Ⅱ Java版本
2 parents ff2fcae + 5eab205 commit 1244f1d

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

problems/回溯算法去重问题的另一种写法.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,45 @@ used数组可是全局变量,每层与每层之间公用一个used数组,所
249249
250250
251251
Java:
252+
**47.全排列II**
253+
254+
255+
```java
256+
class Solution {
257+
private List<List<Integer>> res = new ArrayList<>();
258+
private List<Integer> path = new ArrayList<>();
259+
private boolean[] used = null;
260+
261+
public List<List<Integer>> permuteUnique(int[] nums) {
262+
used = new boolean[nums.length];
263+
Arrays.sort(nums);
264+
backtracking(nums);
265+
return res;
266+
}
267+
268+
public void backtracking(int[] nums) {
269+
if (path.size() == nums.length) {
270+
res.add(new ArrayList<>(path));
271+
return;
272+
}
273+
HashSet<Integer> hashSet = new HashSet<>();//层去重
274+
for (int i = 0; i < nums.length; i++) {
275+
if (hashSet.contains(nums[i]))
276+
continue;
277+
if (used[i] == true)//枝去重
278+
continue;
279+
hashSet.add(nums[i]);//记录元素
280+
used[i] = true;
281+
path.add(nums[i]);
282+
backtracking(nums);
283+
path.remove(path.size() - 1);
284+
used[i] = false;
285+
}
286+
}
287+
}
288+
289+
```
290+
252291

253292
Python:
254293

0 commit comments

Comments
 (0)