```python
###46.全排列
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
def dfs(nums, size, depth, path, used, res):
if depth == size:
res.append(path.copy())
return
for i in range(size):
if not used[i]:
used[i] = True
path.append(nums[i])
dfs(nums, size, depth + 1, path, used, res)
used[i] = False
path.pop()
size = len(nums)
if len(nums) == 0:
return []
used = [False for _ in range(size)]
res = []
dfs(nums, size, 0, [], used, res)
return res
```
```python
###78.子集
class Solution:####这个方法太逆天了
def subsets(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
res=[]
path=[]
def dfs(i):
if i==n:
res.append(path.copy())
return
dfs(i+1)
path.append(nums[i])
print(path,res)
dfs(i+1)
path.pop()
dfs(0)
return res
###这个才能勉强理解
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
n = len(nums)
def dfs(i, tem):
res.append(tem)
for j in range(i,n):
dfs(j+1,tem+[nums[j]])
dfs(0,[])
return res
```
```python
##17.电话号码的组合##纯手撕,有点小激动
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
hs = {'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
n = len(digits)
res = []
if len(digits)==1:
return [x for x in hs[digits]]
if not digits: return []
def dfs(j, tem):
if len(tem)==n:
res.append(tem)
return
for k in hs[digits[j]]:
dfs(j+1,tem+k)
dfs(0,'')
return res
```
```python
##39.组合总和
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
def dfs(candidates, begin, size, path, res, target):
if target <0: return
if target==0:
res.append(path)
return
for index in range(begin,n):
dfs(candidates,index,n,path+[candidates[index]],res,target-candidates[index])
n = len(candidates)
if n == 0:
return []
path = []
res = []
dfs(candidates,0,n,path,res,target)
return res
```
```python
##22.括号生成
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n == 0:
return []
total_l = []
total_l.append([None]) # 0组括号时记为None
total_l.append(["()"]) # 1组括号只有一种情况
for i in range(2,n+1): # 开始计算i组括号时的括号组合
l = []
for j in range(i): # 开始遍历 p q ,其中p+q=i-1 , j 作为索引
now_list1 = total_l[j] # p = j 时的括号组合情况
now_list2 = total_l[i-1-j] # q = (i-1) - j 时的括号组合情况
for k1 in now_list1:
for k2 in now_list2:
if k1 == None:
k1 = ""
if k2 == None:
k2 = ""
el = "(" + k1 + ")" + k2
l.append(el)# 把所有可能的情况添加到 l 中
total_l.append(l)# l这个list就是i组括号的所有情况,添加到total_l中,继续求解i=i+1的情况
return total_l[n]
##深度优先搜索
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []
st = ''
def dfs(st,left,right):
if left == 0 and right == 0:
res.append(st)
return
if right < left:
return
if left >0:
dfs(st+'(',left-1,right)
if right>0:
dfs(st+')',left,right-1)
dfs(st,n,n)
return res
##广度优先搜索
```
```python
###79. 单词搜索
#深度优先搜索
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def dfs(i,j,k):
if not 0<=i<m or not 0<=j<n or board[i][j] != word[k]: return False
if k == len(word)-1: return True
board[i][j] = ''
res = dfs(i+1,j,k+1) or dfs(i-1,j,k+1) or dfs(i,j+1,k+1) or dfs(i,j-1,k+1)
board[i][j] = word[k]
return res
path = []
m,n = len(board), len(board[0])
for i in range(m):
for j in range(n):
if dfs(i,j,0): return True
return False
```
```python
131. 分割回文串
#深度优先搜索
class Solution:
def partition(self, s: str) -> List[List[str]]:
ans=[]
path=[]
n=len(s)
def dfs(i):
if i==n:
ans.append(path.copy())
return
for j in range(i,n):
t = s[i:j+1]
if t == t[::-1]:
path.append(t)
dfs(j+1)
path.pop()
dfs(0)
return ans
##
class Solution:
def partition(self, s: str) -> List[List[str]]:
n = len(s)
dp = [[False]*n for _ in range(n)]
for i in range(n):
for j in range(i+1):
if (s[i]==s[j]) and (i-j<=2 or dp[j+1][i-1]):
dp[j][i] = True
res = []
print(dp)
def helper(i,tmp):
print(tmp,i)
if i == n:
res.append(tmp)
for j in range(i,n):
if dp[i][j]:
helper(j+1,tmp+[s[i:j+1]])
helper(0,[])
return res
```
```python
###79. 单词搜索
#二分法 求得在一般区间的数的数目较大的部分
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
n = len(nums)
l, r = 1, n-1
while l<r:
mid = (l+r)//2
count = 0
for num in nums:
if num <= mid:
count+=1
if count > mid:
r = mid
else:
l = mid+1
return r
##
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
# 快慢指针
slow, fast = 0, 0
while True:
fast = nums[nums[fast]]###key:fast以两倍速度,关键两倍速度和一倍速度碰上,就是重复数
slow = nums[slow]
print(fast,slow)
if slow == fast:
# 找到入口
head = 0
while head != slow:
head = nums[head]
slow = nums[slow]
return head
```
每日刷题--回溯
于 2024-09-06 23:46:05 首次发布