From 68f6c46a1434bedd732f24c082ff920f81fd9e88 Mon Sep 17 00:00:00 2001 From: Jhonson Date: Wed, 20 Oct 2021 21:30:30 +0800 Subject: [PATCH] =?UTF-8?q?[=E5=9B=9E=E6=BA=AF=E7=AE=97=E6=B3=95=E5=8E=BB?= =?UTF-8?q?=E9=87=8D=E9=97=AE=E9=A2=98=E7=9A=84=E5=8F=A6=E4=B8=80=E7=A7=8D?= =?UTF-8?q?=E5=86=99=E6=B3=95.md]=20add=20python=20code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...溯算法去重问题的另一种写法.md | 77 ++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/problems/回溯算法去重问题的另一种写法.md b/problems/回溯算法去重问题的另一种写法.md index 8e92b95b..d8125e91 100644 --- a/problems/回溯算法去重问题的另一种写法.md +++ b/problems/回溯算法去重问题的另一种写法.md @@ -250,9 +250,84 @@ used数组可是全局变量,每层与每层之间公用一个used数组,所 Java: - Python: +**90.子集II** + +```python +class Solution: + def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: + res = [] + nums.sort() + def backtracking(start, path): + res.append(path) + uset = set() + for i in range(start, len(nums)): + if nums[i] not in uset: + backtracking(i + 1, path + [nums[i]]) + uset.add(nums[i]) + + backtracking(0, []) + return res +``` + +**40. 组合总和 II** + +```python +class Solution: + def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: + + res = [] + candidates.sort() + + def backtracking(start, path): + if sum(path) == target: + res.append(path) + elif sum(path) < target: + used = set() + for i in range(start, len(candidates)): + if candidates[i] in used: + continue + else: + used.add(candidates[i]) + backtracking(i + 1, path + [candidates[i]]) + + backtracking(0, []) + + return res +``` + +**47. 全排列 II** + +```python +class Solution: + def permuteUnique(self, nums: List[int]) -> List[List[int]]: + path = [] + res = [] + used = [False]*len(nums) + + def backtracking(): + if len(path) == len(nums): + res.append(path.copy()) + + deduplicate = set() + for i, num in enumerate(nums): + if used[i] == True: + continue + if num in deduplicate: + continue + used[i] = True + path.append(nums[i]) + backtracking() + used[i] = False + path.pop() + deduplicate.add(num) + + backtracking() + + return res +``` + Go: