https://leetcode.cn/problems/combinations/description/
python
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
ans = []
path = []
def dfs(n: int) -> None:
d = k - len(path)
# d表示还需要的长度
if d == 0:
ans.append(path.copy())
return
for i in range(n, d - 1, -1):
# 左开右闭,当剩余的数字不足够d(所需要的长度)时结束循环
path.append(i)
dfs(i - 1)
path.pop()
dfs(n)
return ans
https://leetcode.cn/problems/combination-sum-iii/description/
python
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
ans = []
path = []
curSum = 0
def dfs(i:int) -> None:
nonlocal curSum
d = n - curSum
if k - len(path) > i or d < 0:
# 剪枝
return
if d == 0 and len(path) == k:
ans.append(path[:])
return
for j in range(i, 0, -1):
curSum += j
path.append(j)
dfs(j - 1)
curSum -= j
path.pop()
dfs(9)
return ans
https://leetcode.cn/problems/letter-combinations-of-a-phone-number/description/
python
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits: return []
res = []
phone = {'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']}
def backtrack(conbination, nextdigit):
if len(nextdigit) == 0:
res.append(conbination)
return
else:
for letter in phone[nextdigit[0]]:
backtrack(conbination + letter, nextdigit[1:])
backtrack('', digits)
return res