mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-12 05:20:59 +08:00
添加0046.全排列新解法Java代码
This commit is contained in:
@ -183,6 +183,32 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
```java
|
||||||
|
// 解法2:通过判断path中是否存在数字,排除已经选择的数字
|
||||||
|
class Solution {
|
||||||
|
List<List<Integer>> result = new ArrayList<>();
|
||||||
|
LinkedList<Integer> path = new LinkedList<>();
|
||||||
|
public List<List<Integer>> permute(int[] nums) {
|
||||||
|
if (nums.length == 0) return result;
|
||||||
|
backtrack(nums, path);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
public void backtrack(int[] nums, LinkedList<Integer> path) {
|
||||||
|
if (path.size() == nums.length) {
|
||||||
|
result.add(new ArrayList<>(path));
|
||||||
|
}
|
||||||
|
for (int i =0; i < nums.length; i++) {
|
||||||
|
// 如果path中已有,则跳过
|
||||||
|
if (path.contains(nums[i])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
path.add(nums[i]);
|
||||||
|
backtrack(nums, path);
|
||||||
|
path.removeLast();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
```python3
|
```python3
|
||||||
|
Reference in New Issue
Block a user