From a6c95b78e80f754dc901747046e06008710a639f Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 27 May 2023 19:21:17 -0500 Subject: [PATCH] =?UTF-8?q?Update=200491.=E9=80=92=E5=A2=9E=E5=AD=90?= =?UTF-8?q?=E5=BA=8F=E5=88=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0491.递增子序列.md | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/problems/0491.递增子序列.md b/problems/0491.递增子序列.md index a805a262..50cb9918 100644 --- a/problems/0491.递增子序列.md +++ b/problems/0491.递增子序列.md @@ -272,23 +272,24 @@ class Solution { class Solution: def findSubsequences(self, nums): result = [] - self.backtracking(nums, 0, [], result) + path = [] + self.backtracking(nums, 0, path, result) return result - + def backtracking(self, nums, startIndex, path, result): if len(path) > 1: - result.append(path[:]) # 将当前路径的副本加入结果集 + result.append(path[:]) # 注意要使用切片将当前路径的副本加入结果集 + # 注意这里不要加return,要取树上的节点 - used = set() # 使用集合来进行去重操作 + uset = set() # 使用集合对本层元素进行去重 for i in range(startIndex, len(nums)): - if path and nums[i] < path[-1]: - continue # 如果当前元素小于上一个元素,则跳过当前元素 + if (path and nums[i] < path[-1]) or nums[i] in uset: + continue - if nums[i] in used: - continue # 如果当前元素已经使用过,则跳过当前元素 - - used.add(nums[i]) # 标记当前元素已经使用过 - self.backtracking(nums, i + 1, path + [nums[i]], result) + uset.add(nums[i]) # 记录这个元素在本层用过了,本层后面不能再用了 + path.append(nums[i]) + self.backtracking(nums, i + 1, path, result) + path.pop() ``` 回溯 利用哈希表去重 @@ -314,6 +315,7 @@ class Solution: self.backtracking(nums, i + 1, path, result) path.pop() + ``` ### Go