mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
0090.子集II:优化排版,补充Swift版本
This commit is contained in:
@ -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
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
<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