From b884383b1264da0bf158bcf34ffba62afa754c36 Mon Sep 17 00:00:00 2001 From: bqlin Date: Sun, 12 Dec 2021 18:35:29 +0800 Subject: [PATCH] =?UTF-8?q?0090.=E5=AD=90=E9=9B=86II=EF=BC=9A=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E6=8E=92=E7=89=88=EF=BC=8C=E8=A1=A5=E5=85=85Swift?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0090.子集II.md | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/problems/0090.子集II.md b/problems/0090.子集II.md index 95b6080b..17612801 100644 --- a/problems/0090.子集II.md +++ b/problems/0090.子集II.md @@ -156,14 +156,12 @@ public: 当然本题去重的逻辑,也可以这么写 -``` +```cpp if (i > startIndex && nums[i] == nums[i - 1] ) { - continue; + continue; } ``` - - ## 其他语言版本 @@ -359,6 +357,31 @@ int** subsetsWithDup(int* nums, int numsSize, int* returnSize, int** returnColum } ``` +## Swift + +```swift +func subsetsWithDup(_ nums: [Int]) -> [[Int]] { + let nums = nums.sorted() + var result = [[Int]]() + var path = [Int]() + func backtracking(startIndex: Int) { + // 直接收集结果 + result.append(path) + + let end = nums.count + guard startIndex < end else { return } // 终止条件 + for i in startIndex ..< end { + if i > startIndex, nums[i] == nums[i - 1] { continue } // 跳过重复元素 + path.append(nums[i]) // 处理:收集元素 + backtracking(startIndex: i + 1) // 元素不重复访问 + path.removeLast() // 回溯 + } + } + backtracking(startIndex: 0) + return result +} +``` + -----------------------