【代码随想录训练营】【Day 27 and 28】【回溯1-2】| Leetcode 77, 216, 17
需强化知识点
- 组合问题:感受遍历的横向和纵向
题目
77. 组合
- 注意path要深拷贝
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
result = []
def backtracking(n, k, startIndex, path, result):
if len(path) == k:
result.append(path[:])
return
for i in range(startIndex, n+1):
path.append(i)
backtracking(n, k, i+1, path, result)
path.pop()
backtracking(n, k, 1, [], result)
return result
216. 组合总和 III
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
def backtracking(k, n, start_index, path_sum, path, result):
if len(path) == k and path_sum == n:
result.append(path[:])
return
for i in range(start_index, 10):
path_sum += i
if path_sum > n:
return
path.append(i)
backtracking(k, n, i+1, path_sum, path, result)
path_sum -= i
path.pop()
result = []
backtracking(k, n, 1, 0, [], result)
return result
17. 电话号码的字母组合
- 二刷又有些忘了:数字遍历是纵向遍历(startIndex控制),字母遍历是横向遍历(for循环)
- 字符串,加: +=,减:str = str[:-1]
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
letter_dict = {2:"abc", 3:"def", 4:"ghi", 5:"jkl", 6:"mno", 7:"pqrs", 8:"tuv", 9:"wxyz"}
result = []
if len(digits) == 0:
return [ ]
def backtracking(digits, letter_dict, start_index, path, result):
if len(path) == len(digits):
result.append("".join(path))
return
letters = letter_dict[int(digits[start_index])]
for letter in letters:
path.append(letter)
backtracking(digits, letter_dict, start_index+1, path, result)
path.pop()
backtracking(digits, letter_dict, 0, [], result)
return result