另一种写法 全排列Ⅱ Java

This commit is contained in:
Younglesszzz
2021-10-27 20:03:18 +08:00
parent ecb4292a4a
commit 5eab2050cf

View File

@ -249,6 +249,45 @@ used数组可是全局变量每层与每层之间公用一个used数组
Java Java
**47.全排列II**
```java
class Solution {
private List<List<Integer>> res = new ArrayList<>();
private List<Integer> path = new ArrayList<>();
private boolean[] used = null;
public List<List<Integer>> permuteUnique(int[] nums) {
used = new boolean[nums.length];
Arrays.sort(nums);
backtracking(nums);
return res;
}
public void backtracking(int[] nums) {
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
HashSet<Integer> hashSet = new HashSet<>();//层去重
for (int i = 0; i < nums.length; i++) {
if (hashSet.contains(nums[i]))
continue;
if (used[i] == true)//枝去重
continue;
hashSet.add(nums[i]);//记录元素
used[i] = true;
path.add(nums[i]);
backtracking(nums);
path.remove(path.size() - 1);
used[i] = false;
}
}
}
```
Python Python