LeetCode 216 组合总和III
题目链接:216. 组合总和 III - 力扣(Leetcode)
这道题和77 组合解题思路完全相同,只是收集结果时多加了和为n的限制。具体代码实现时一度出现重复使用数字的情况,debug发现是for循环中调用递归函数时,每次遍历起始数字start传入了start+1,导致下一层遍历的起始位置有出入(可以获得已经遍历过的值),正确做法应该是传入当前i的下一个数字,限制下一层可遍历的范围:
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
result, path = [], []
def backtracking(start, remain):
if remain < 0:
return
if len(path) == k:
if remain == 0:
result.append(path[:])
return
end = 9 - (k - len(path)) + 1
for i in range(start, end + 1):
path.append(i)
backtracking(i+1, remain-i)
path.pop()
backtracking(1, n)
return result
LeetCode 17 电话号码的字母组合
题目链接:17. 电话号码的字母组合 - 力扣(Leetcode)
这道题的回溯本质上和数字的组合没什么不同,只是组合形式多了一个映射关系。递归函数传入的idx是当前遍历到的数字下标,for循环遍历的就是当前数字对应的字母序列,深度优先遍历使得函数一直递归到digits最后一个数字才开始收集结果,不断回溯,最终得到所有组合结果:
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if len(digits) == 0:
return []
digit_map = {'2':'abc', '3':'def', '4': 'ghi', '5':'jkl', '6':'mno', '7':'pqrs', '8':'tuv', '9':'wxyz'}
path, res = [] , []
def backtracking(idx):
if idx == len(digits):
res.append(''.join(path.copy()))
return
chs = digit_map[digits[idx]]
for ch in chs:
path.append(ch)
backtracking(idx + 1)
path.pop()
backtracking(0)
return res
今天的回溯就先复习到这吧。