From a953eca2342b74be1255a3d1a9359b37a2044526 Mon Sep 17 00:00:00 2001 From: bqlin Date: Mon, 13 Dec 2021 15:54:48 +0800 Subject: [PATCH] =?UTF-8?q?0047.=E5=85=A8=E6=8E=92=E5=88=97II=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/0047.全排列II.md | 38 ++++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/problems/0047.全排列II.md b/problems/0047.全排列II.md index d5d1528b..167e4b76 100644 --- a/problems/0047.全排列II.md +++ b/problems/0047.全排列II.md @@ -97,14 +97,15 @@ public: 大家发现,去重最为关键的代码为: -``` +```cpp if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) { continue; } ``` **如果改成 `used[i - 1] == true`, 也是正确的!**,去重代码如下: -``` + +```cpp if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == true) { continue; } @@ -131,13 +132,13 @@ if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == true) { ## 总结 这道题其实还是用了我们之前讲过的去重思路,但有意思的是,去重的代码中,这么写: -``` +```cpp if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) { continue; } ``` 和这么写: -``` +```cpp if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == true) { continue; } @@ -291,7 +292,36 @@ var permuteUnique = function (nums) { ``` +### Swift +```swift +func permuteUnique(_ nums: [Int]) -> [[Int]] { + let nums = nums.sorted() // 先排序,以方便相邻元素去重 + var result = [[Int]]() + var path = [Int]() + var used = [Bool](repeating: false, count: nums.count) + func backtracking() { + if path.count == nums.count { + result.append(path) + return + } + + for i in 0 ..< nums.count { + // !used[i - 1]表示同一树层nums[i - 1]使用过,直接跳过,这一步很关键! + if i > 0, nums[i] == nums[i - 1], !used[i - 1] { continue } + if used[i] { continue } + used[i] = true + path.append(nums[i]) + backtracking() + // 回溯 + path.removeLast() + used[i] = false + } + } + backtracking() + return result +} +``` -----------------------