添加0046.全排列新解法Java代码

This commit is contained in:
ironartisan
2021-08-29 18:55:36 +08:00
parent 051c2c5c3e
commit 615139b74d

View File

@ -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
```python3