Skip to content

Commit 07dd850

Browse files
authored
Update 0491.递增子序列.md
补全python代码补充注释
1 parent e447076 commit 07dd850

File tree

1 file changed

+69
-20
lines changed

1 file changed

+69
-20
lines changed

problems/0491.递增子序列.md

Lines changed: 69 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -229,32 +229,81 @@ class Solution {
229229
}
230230
}
231231
```
232-
233-
234232
Python:
233+
**回溯**
235234
```python3
236235
class Solution:
236+
def __init__(self):
237+
self.paths = []
238+
self.path = []
239+
237240
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
238-
res = []
239-
path = []
240-
def backtrack(nums,startIndex):
241-
repeat = [] #这里使用数组来进行去重操作
242-
if len(path) >=2:
243-
res.append(path[:]) #注意这里不要加return,要取树上的节点
244-
for i in range(startIndex,len(nums)):
245-
if nums[i] in repeat:
246-
continue
247-
if len(path) >= 1:
248-
if nums[i] < path[-1]:
249-
continue
250-
repeat.append(nums[i]) #记录这个元素在本层用过了,本层后面不能再用了
251-
path.append(nums[i])
252-
backtrack(nums,i+1)
253-
path.pop()
254-
backtrack(nums,0)
255-
return res
241+
'''
242+
本题求自增子序列,所以不能改变原数组顺序
243+
'''
244+
self.backtracking(nums, 0)
245+
return self.paths
246+
247+
def backtracking(self, nums: List[int], start_index: int):
248+
# 收集结果,同78.子集,仍要置于终止条件之前
249+
if len(self.path) >= 2:
250+
# 本题要求所有的节点
251+
self.paths.append(self.path[:])
252+
253+
# Base Case(可忽略)
254+
if start_index == len(nums):
255+
return
256+
257+
# 单层递归逻辑
258+
# 深度遍历中每一层都会有一个全新的usage_list用于记录本层元素是否重复使用
259+
usage_list = set()
260+
# 同层横向遍历
261+
for i in range(start_index, len(nums)):
262+
# 若当前元素值小于前一个时(非递增)或者曾用过,跳入下一循环
263+
if (self.path and nums[i] < self.path[-1]) or nums[i] in usage_list:
264+
continue
265+
usage_list.add(nums[i])
266+
self.path.append(nums[i])
267+
self.backtracking(nums, i+1)
268+
self.path.pop()
256269
```
270+
**回溯+哈希表去重**
271+
```python3
272+
class Solution:
273+
def __init__(self):
274+
self.paths = []
275+
self.path = []
257276

277+
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
278+
'''
279+
本题求自增子序列,所以不能改变原数组顺序
280+
'''
281+
self.backtracking(nums, 0)
282+
return self.paths
283+
284+
def backtracking(self, nums: List[int], start_index: int):
285+
# 收集结果,同78.子集,仍要置于终止条件之前
286+
if len(self.path) >= 2:
287+
# 本题要求所有的节点
288+
self.paths.append(self.path[:])
289+
290+
# Base Case(可忽略)
291+
if start_index == len(nums):
292+
return
293+
294+
# 单层递归逻辑
295+
# 深度遍历中每一层都会有一个全新的usage_list用于记录本层元素是否重复使用
296+
usage_list = [False] * 201 # 使用列表去重,题中取值范围[-100, 100]
297+
# 同层横向遍历
298+
for i in range(start_index, len(nums)):
299+
# 若当前元素值小于前一个时(非递增)或者曾用过,跳入下一循环
300+
if (self.path and nums[i] < self.path[-1]) or usage_list[nums[i]+100] == True:
301+
continue
302+
usage_list[nums[i]+100] = True
303+
self.path.append(nums[i])
304+
self.backtracking(nums, i+1)
305+
self.path.pop()
306+
```
258307
Go:
259308

260309
```golang

0 commit comments

Comments
 (0)