mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Update 0491.递增子序列.md
This commit is contained in:
@ -272,23 +272,24 @@ class Solution {
|
|||||||
class Solution:
|
class Solution:
|
||||||
def findSubsequences(self, nums):
|
def findSubsequences(self, nums):
|
||||||
result = []
|
result = []
|
||||||
self.backtracking(nums, 0, [], result)
|
path = []
|
||||||
|
self.backtracking(nums, 0, path, result)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def backtracking(self, nums, startIndex, path, result):
|
def backtracking(self, nums, startIndex, path, result):
|
||||||
if len(path) > 1:
|
if len(path) > 1:
|
||||||
result.append(path[:]) # 将当前路径的副本加入结果集
|
result.append(path[:]) # 注意要使用切片将当前路径的副本加入结果集
|
||||||
|
# 注意这里不要加return,要取树上的节点
|
||||||
|
|
||||||
used = set() # 使用集合来进行去重操作
|
uset = set() # 使用集合对本层元素进行去重
|
||||||
for i in range(startIndex, len(nums)):
|
for i in range(startIndex, len(nums)):
|
||||||
if path and nums[i] < path[-1]:
|
if (path and nums[i] < path[-1]) or nums[i] in uset:
|
||||||
continue # 如果当前元素小于上一个元素,则跳过当前元素
|
continue
|
||||||
|
|
||||||
if nums[i] in used:
|
uset.add(nums[i]) # 记录这个元素在本层用过了,本层后面不能再用了
|
||||||
continue # 如果当前元素已经使用过,则跳过当前元素
|
path.append(nums[i])
|
||||||
|
self.backtracking(nums, i + 1, path, result)
|
||||||
used.add(nums[i]) # 标记当前元素已经使用过
|
path.pop()
|
||||||
self.backtracking(nums, i + 1, path + [nums[i]], result)
|
|
||||||
|
|
||||||
```
|
```
|
||||||
回溯 利用哈希表去重
|
回溯 利用哈希表去重
|
||||||
@ -314,6 +315,7 @@ class Solution:
|
|||||||
self.backtracking(nums, i + 1, path, result)
|
self.backtracking(nums, i + 1, path, result)
|
||||||
path.pop()
|
path.pop()
|
||||||
|
|
||||||
|
|
||||||
```
|
```
|
||||||
### Go
|
### Go
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user