diff --git a/problems/0491.递增子序列.md b/problems/0491.递增子序列.md index 231ea494..ee7180dd 100644 --- a/problems/0491.递增子序列.md +++ b/problems/0491.递增子序列.md @@ -56,7 +56,7 @@ 代码如下: -``` +```cpp vector> result; vector path; void backtracking(vector& nums, int startIndex) @@ -68,7 +68,7 @@ void backtracking(vector& nums, int startIndex) 但本题收集结果有所不同,题目要求递增子序列大小至少为2,所以代码如下: -``` +```cpp if (path.size() > 1) { result.push_back(path); // 注意这里不要加return,因为要取树上的所有节点 @@ -82,7 +82,7 @@ if (path.size() > 1) { 那么单层搜索代码如下: -``` +```cpp unordered_set uset; // 使用set来对本层元素进行去重 for (int i = startIndex; i < nums.size(); i++) { if ((!path.empty() && nums[i] < path.back()) @@ -431,6 +431,36 @@ int** findSubsequences(int* nums, int numsSize, int* returnSize, int** returnCol } ``` +## Swift + +```swift +func findSubsequences(_ nums: [Int]) -> [[Int]] { + var result = [[Int]]() + var path = [Int]() + func backtracking(startIndex: Int) { + // 收集结果,但不返回,因为后续还要以此基础拼接 + if path.count > 1 { + result.append(path) + } + + var uset = Set() + let end = nums.count + guard startIndex < end else { return } // 终止条件 + for i in startIndex ..< end { + let num = nums[i] + if uset.contains(num) { continue } // 跳过重复元素 + if !path.isEmpty, num < path.last! { continue } // 确保递增 + uset.insert(num) // 通过set记录 + path.append(num) // 处理:收集元素 + backtracking(startIndex: i + 1) // 元素不重复访问 + path.removeLast() // 回溯 + } + } + backtracking(startIndex: 0) + return result +} +``` + -----------------------