mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
0491.递增子序列:优化排版,补充Swift版本
This commit is contained in:
@ -56,7 +56,7 @@
|
||||
|
||||
代码如下:
|
||||
|
||||
```
|
||||
```cpp
|
||||
vector<vector<int>> result;
|
||||
vector<int> path;
|
||||
void backtracking(vector<int>& nums, int startIndex)
|
||||
@ -68,7 +68,7 @@ void backtracking(vector<int>& 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<int> 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<Int>()
|
||||
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
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
<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