216.组合总和III
思路:
和77. 组合思路一致,只不过多了一个cursum用来记录总和。
代码:
class Solution:def combinationSum3(self, k: int, n: int) -> List[List[int]]:path = []result = []def backtracking( k, n, start, cursum):if len(path) == k and cursum == n:result.append(path[ : ])for i in range(start, 10):cursum += ipath.append(i)backtracking(k, n, i+1, cursum)path.pop()cursum -= ibacktracking(k, n, 1, 0)return result
17.电话号码的字母组合
思路:
先做出数字与字母的对应,这里使用列表实现。
使用index遍历digits(题目给的数字),每递归一次,index加1
使用letters表示数字代表的字母,并使用for循环遍历
代码:
class Solution:def letterCombinations(self, digits: str) -> List[str]:# 定义电话号码对应的字母表phone = ['', '', 'abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']# 初始化路径和结果path = str()result = []def backtracking(digits, index):nonlocal path # 使用nonlocal声明path为外部变量if len(digits) == index:result.append(path)returndigit = int(digits[index])letters = phone[digit]for i in range(len(letters)):path += letters[i]backtracking(digits, index + 1)path = path[:-1] # 回溯,移除最后一个字母# 特殊情况处理:如果digits为空,则直接返回空结果if len(digits) == 0:return result# 调用回溯函数,从索引0开始backtracking(digits, 0)return result