mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
[回溯算法去重问题的另一种写法.md] add python code
This commit is contained in:
@ -250,9 +250,84 @@ used数组可是全局变量,每层与每层之间公用一个used数组,所
|
|||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
|
||||||
|
|
||||||
Python:
|
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:
|
Go:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user