216.组合总和III
题目链接:216. 组合总和III
思路:终止条件的确定需要仔细思考,由于倒数第二个数确认后,最后一个数也随之确认,所以终止条件是 k == 1
。其次不是每个终止条件所得到的结果都符合题目要求,因此需要增加判断n > ans[-1] and n < 10
,在终止条件内处理完节点后别忘了撤销结果。
class Solution:
def _combination_sum3(self, k: int, n: int, start: int, res: List[List[int]], ans: List[int]):
if k == 1:
if n > ans[-1] and n < 10:
ans.append(n)
res.append(ans.copy())
ans.pop()
return
for i in range(start, 10):
ans.append(i)
self._combination_sum3(k-1, n - i, i + 1, res, ans)
ans.pop()
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res = []
self._combination_sum3(k, n, 1, res, [])
return res
17.电话号码的字母组合
题目链接:17.电话号码的字母组合
思路:这题每个集合遍历的宽度不一样,一开始有点没转过弯来。不过完全能用回溯模板来套,只不过需要自行构造不等长的横向遍历
class Solution:
def _letter_combinations(self, digits: str, index: int, num_letter_map: Dict[str, str], res: List[str], ans: str):
if index == len(digits):
res.append(ans)
return
for char in num_letter_map[digits[index]]:
ans += char
self._letter_combinations(digits, index + 1, num_letter_map, res, ans)
ans = ans[:-1]
def letterCombinations(self, digits: str) -> List[str]:
res = []
if digits:
num_letter_map = {
"2": "abc", "3": "def",
"4" : "ghi", "5": "jkl", "6": "mno",
"7": "pqrs", "8": "tuv", "9": "wxyz"
}
self._letter_combinations(digits, 0, num_letter_map, res, "")
return res