classSolution:defletterCombinations(self, digits:str)-> List[str]:ifnot digits:return[]
phone =['abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
queue =['']# 初始化队列for digit in digits:for _ inrange(len(queue)):
tmp = queue.pop(0)for letter in phone[ord(digit)-50]:
queue.append(tmp + letter)return queue
22 括号生成
classSolution:defgenerateParenthesis(self, n:int)-> List[str]:
ans =[]# 根据n初始化可以使用的左括号和右括号数# open代表可以使用的左括号数,close代表可以使用的右括号数defdfs(s,open, close, res):# 如果可以使用的右括号数小于左括号数,说明这种搭配错误,停止分裂if close <open:return# 如果左括号用完了,直接把剩下的右括号加上,加入返回数组ifopen==0:
tmp = close *')'
s += tmp
res.append(s)else:# 下一步分出两种选择,左括号和右括号,对应的左右括号数变化
dfs(s +'(',open-1, close, res)
dfs(s +')',open, close -1, res)
dfs('', n, n, ans)return ans
37 解数独
classSolution:defsolveSudoku(self, board):"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""defcheck(x, y, s):# 行列是否冲突for i inrange(9):if board[i][y]== s or board[x][i]== s:returnFalse# box是否冲突for i in[0,1,2]:for j in[0,1,2]:if board[x//3*3+i][y//3*3+j]== s:returnFalsereturnTruedefbt(cur):if cur ==81:returnTrue
x, y = cur //9, cur %9if board[x][y]!='.':return bt(cur +1)for i inrange(1,10):
s =str(i)if check(x, y, s):# 设置该值
board[x][y]= s
# 进行递归检查冲突if bt(cur +1):returnTrue# 填充失败,回溯
board[x][y]='.'returnFalse
bt(0)
39 组合总和
classSolution:defcombinationSum(self, candidates: List[int], target:int)-> List[List[int]]:
candidates =sorted(candidates)
res =[]
len_list =len(candidates)defhelper(target, path, start):nonlocal res
nonlocal candidates
nonlocal len_list
if target ==0:
res.append(path.copy())for i inrange(start, len_list):if target - candidates[i]<0:break
path.append(candidates[i])
helper(target - candidates[i], path, i)
path.pop()
helper(target,[],0)return res
40 组合总和II
classSolution:defcombinationSum2(self, candidates: List[int], target:int)-> List[List[int]]:
candidates =sorted(candidates)
res =[]
len_list =len(candidates)defhelper(target, path, start):nonlocal res
nonlocal candidates
nonlocal len_list
if target ==0:
res.append(path.copy())for i inrange(start, len_list):if target - candidates[i]<0:break# 去重if i > start and candidates[i]== candidates[i-1]:continue
path.append(candidates[i])# 和I的区别就在于1.需要去重2.不包含自己
helper(target - candidates[i], path, i +1)
path.pop()
helper(target,[],0)return res