216.组合总和III
解法:回溯 + 减枝
回溯三部曲:
1.确定递归函数参数
2.确定终止条件
3.回溯搜索的遍历过程
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
total = 0
res = []
path = []
def backtracking(k,n,startindex):
nonlocal total
if len(path) == k:
if total == n:
res.append(path[:])
return
if total > n: #剪枝
return
for i in range(startindex,10 - (k-len(path))+1):
path.append(i)
total += i
backtracking(k,n,i+1)
path.pop()
total -= i
backtracking(k,n,1)
return res
17.电话号码的字母组合
解法:回溯(两层嵌套)
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return []
res = []
dic = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
def backtracking(digits,index,string):
if index == len(digits):
res.append(string)
return
letter = dic[digits[index]]
for i in letter:
backtracking(digits,index+1,string+i)
backtracking(digits,0,'')
return res