思路:使用回溯三部曲!① 确认需要传入的参数以及返回值 ② 回溯的终止条件 ③ 单层搜索的逻辑!这道题易错点在于单层的逻辑上的遍历起始位置以及回溯回退步骤里要执行的内容!
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
result = []
self.backtrack(k, n, 1,[], 0, result)
return result
def backtrack(self, k, n, start,temp_res,target, result):
if k == 0:
if target == n:
result.append(temp_res[:])
return
for i in range(start, 10):
if target > n:
continue
temp_res.append(i)
target += i
self.backtrack(k - 1, n, i + 1, temp_res, target, result)
temp_res.pop()
target -= i
核心:依旧是回溯三部曲!有个点需要注意的是"".join(res),如果res是空的话,那么最终内容会是这样的[ “” ]而不是[ ]这样了!还不需要进行剪枝
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
dict_ziwu = {"2":['a','b','c'],"3":["d","e","f"],"4":["g","h","i"],
"5":["j","k","l"],"6":["m","n","o"],"7":["p","q","r","s"],"8":["t","u","v"],"9":["w","x","y","z"]}
length = len(digits)
result = []
self.backtrack(digits,0,length,[],result,dict_ziwu)
return result
def backtrack(self, str1, start, length, res, result,dict_ziwu):
if start == length:
if res:
result.append("".join(res))
return
list_temp = dict_ziwu[str1[start]]
for _list in list_temp:
res.append(_list)
start += 1
self.backtrack(str1,start,length,res,result,dict_ziwu)
res.pop()
start -= 1
class Solution:
def __init__(self):
self.letterMap = [
"",
"",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
]
self.result = []
self.s = ""
def backtracking(self, digits, index):
if index == len(digits):
self.result.append(self.s)
return
digit = int(digits[index])
letters = self.letterMap[digit]
for i in range(len(letters)):
self.s += letters[i]
self.backtracking(digits, index + 1)
self.s = self.s[:-1]
def letterCombinations(self, digits):
if len(digits) == 0:
return self.result
self.backtracking(digits, 0)
return self.result