代码随想录文章讲解
回溯+剪枝
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
path = []
res = []
def _backtracking(k, n, path_sum, num):
nonlocal path
nonlocal res
if path_sum > n:
return
if len(path) == k:
if sum(path) == n:
res.append(path[:])
return
for i in range(num, 10 - (k - len(path)) + 1):
path.append(i)
_backtracking(k, n, path_sum + i, i+1)
path.pop()
_backtracking(k, n, 0, 1)
return res
代码随想录文章讲解
回溯法
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return []
nums_letter_map = {
'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']
}
letter_comb = ''
res = []
def _backtracking(n, idx):
nonlocal letter_comb
nonlocal res
nonlocal nums_letter_map
nonlocal digits
if len(letter_comb) == n:
res.append(letter_comb)
return
d = digits[idx]
for l in nums_letter_map[d]:
letter_comb += l
_backtracking(n, idx + 1)
letter_comb = letter_comb[:-1]
_backtracking(len(digits), 0)
return res