mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
补充其他语言版本
This commit is contained in:
@ -147,6 +147,79 @@ if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == true) {
|
||||
|
||||
是不是豁然开朗了!!
|
||||
|
||||
## 其他语言版本
|
||||
|
||||
java:
|
||||
|
||||
```java
|
||||
class Solution {
|
||||
//存放结果
|
||||
List<List<Integer>> result = new ArrayList<>();
|
||||
//暂存结果
|
||||
List<Integer> path = new ArrayList<>();
|
||||
|
||||
public List<List<Integer>> permuteUnique(int[] nums) {
|
||||
boolean[] used = new boolean[nums.length];
|
||||
Arrays.fill(used, false);
|
||||
Arrays.sort(nums);
|
||||
backTrack(nums, used);
|
||||
return result;
|
||||
}
|
||||
|
||||
private void backTrack(int[] nums, boolean[] used) {
|
||||
if (path.size() == nums.length) {
|
||||
result.add(new ArrayList<>(path));
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
// used[i - 1] == true,说明同⼀树⽀nums[i - 1]使⽤过
|
||||
// used[i - 1] == false,说明同⼀树层nums[i - 1]使⽤过
|
||||
// 如果同⼀树层nums[i - 1]使⽤过则直接跳过
|
||||
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
|
||||
continue;
|
||||
}
|
||||
//如果同⼀树⽀nums[i]没使⽤过开始处理
|
||||
if (used[i] == false) {
|
||||
used[i] = true;//标记同⼀树⽀nums[i]使⽤过,防止同一树支重复使用
|
||||
path.add(nums[i]);
|
||||
backTrack(nums, used);
|
||||
path.remove(path.size() - 1);//回溯,说明同⼀树层nums[i]使⽤过,防止下一树层重复
|
||||
used[i] = false;//回溯
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
python:
|
||||
|
||||
```python
|
||||
class Solution:
|
||||
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
|
||||
# res用来存放结果
|
||||
if not nums: return []
|
||||
res = []
|
||||
used = [0] * len(nums)
|
||||
def backtracking(nums, used, path):
|
||||
# 终止条件
|
||||
if len(path) == len(nums):
|
||||
res.append(path.copy())
|
||||
return
|
||||
for i in range(len(nums)):
|
||||
if not used[i]:
|
||||
if i>0 and nums[i] == nums[i-1] and not used[i-1]:
|
||||
continue
|
||||
used[i] = 1
|
||||
path.append(nums[i])
|
||||
backtracking(nums, used, path)
|
||||
path.pop()
|
||||
used[i] = 0
|
||||
# 记得给nums排序
|
||||
backtracking(sorted(nums),used,[])
|
||||
return res
|
||||
```
|
||||
|
||||
|
||||
> **相信很多小伙伴刷题的时候面对力扣上近两千道题目,感觉无从下手,我花费半年时间整理了Github项目:「力扣刷题攻略」[https://github.com/youngyangyang04/leetcode-master](https://github.com/youngyangyang04/leetcode-master)。 里面有100多道经典算法题目刷题顺序、配有40w字的详细图解,常用算法模板总结,以及难点视频讲解,按照list一道一道刷就可以了!star支持一波吧!**
|
||||
|
||||
* 公众号:[代码随想录](https://img-blog.csdnimg.cn/20201210231711160.png)
|
||||
|
Reference in New Issue
Block a user