mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
0046.全排列:优化排版,补充Swift版本
This commit is contained in:
@ -44,7 +44,7 @@
|
||||
|
||||
* 递归函数参数
|
||||
|
||||
**首先排列是有序的,也就是说[1,2] 和[2,1] 是两个集合,这和之前分析的子集以及组合所不同的地方**。
|
||||
**首先排列是有序的,也就是说 [1,2] 和 [2,1] 是两个集合,这和之前分析的子集以及组合所不同的地方**。
|
||||
|
||||
可以看出元素1在[1,2]中已经使用过了,但是在[2,1]中还要在使用一次1,所以处理排列问题就不用使用startIndex了。
|
||||
|
||||
@ -54,7 +54,7 @@
|
||||
|
||||
代码如下:
|
||||
|
||||
```
|
||||
```cpp
|
||||
vector<vector<int>> result;
|
||||
vector<int> path;
|
||||
void backtracking (vector<int>& nums, vector<bool>& used)
|
||||
@ -72,7 +72,7 @@ void backtracking (vector<int>& nums, vector<bool>& used)
|
||||
|
||||
代码如下:
|
||||
|
||||
```
|
||||
```cpp
|
||||
// 此时说明找到了一组
|
||||
if (path.size() == nums.size()) {
|
||||
result.push_back(path);
|
||||
@ -90,7 +90,7 @@ if (path.size() == nums.size()) {
|
||||
|
||||
代码如下:
|
||||
|
||||
```
|
||||
```cpp
|
||||
for (int i = 0; i < nums.size(); i++) {
|
||||
if (used[i] == true) continue; // path里已经收录的元素,直接跳过
|
||||
used[i] = true;
|
||||
@ -179,7 +179,7 @@ class Solution {
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
```java
|
||||
// 解法2:通过判断path中是否存在数字,排除已经选择的数字
|
||||
@ -331,7 +331,8 @@ var permute = function(nums) {
|
||||
|
||||
```
|
||||
|
||||
C:
|
||||
### C
|
||||
|
||||
```c
|
||||
int* path;
|
||||
int pathTop;
|
||||
@ -398,6 +399,35 @@ int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes)
|
||||
}
|
||||
```
|
||||
|
||||
### Swift
|
||||
|
||||
```swift
|
||||
func permute(_ nums: [Int]) -> [[Int]] {
|
||||
var result = [[Int]]()
|
||||
var path = [Int]()
|
||||
var used = [Bool](repeating: false, count: nums.count) // 记录path中已包含的元素
|
||||
func backtracking() {
|
||||
// 结束条件,收集结果
|
||||
if path.count == nums.count {
|
||||
result.append(path)
|
||||
return
|
||||
}
|
||||
|
||||
for i in 0 ..< nums.count {
|
||||
if used[i] { continue } // 排除已包含的元素
|
||||
used[i] = true
|
||||
path.append(nums[i])
|
||||
backtracking()
|
||||
// 回溯
|
||||
path.removeLast()
|
||||
used[i] = false
|
||||
}
|
||||
}
|
||||
backtracking()
|
||||
return result
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user