mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
另一种写法 全排列Ⅱ Java
This commit is contained in:
@ -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:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user