From 39a233f22ff8c15d1561a44e157bafdc38633f33 Mon Sep 17 00:00:00 2001 From: bqlin Date: Mon, 13 Dec 2021 12:00:32 +0800 Subject: [PATCH] =?UTF-8?q?0046.=E5=85=A8=E6=8E=92=E5=88=97=EF=BC=9A?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=8E=92=E7=89=88=EF=BC=8C=E8=A1=A5=E5=85=85?= =?UTF-8?q?Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0046.全排列.md | 42 ++++++++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/problems/0046.全排列.md b/problems/0046.全排列.md index 18005961..a37f6da3 100644 --- a/problems/0046.全排列.md +++ b/problems/0046.全排列.md @@ -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> result; vector path; void backtracking (vector& nums, vector& used) @@ -72,7 +72,7 @@ void backtracking (vector& nums, vector& 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 +} +``` + -----------------------