0491.递增子序列:优化排版,补充Swift版本

This commit is contained in:
bqlin
2021-12-12 19:15:58 +08:00
parent b884383b12
commit cf59acd6c2

View File

@@ -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>