0X00 模板題目
class Solution:
def __init__(self):
self.num_letter = {
'2': "abc",
'3': "def",
'4': "ghi",
'5': "jkl",
'6': "mno",
'7': "pqrs",
'8': "tuv",
'9': "wxyz",
}
def letterCombinations(self, digits: str) -> List[str]:
ans = []
if len(digits) == 0:
return ans
cur = ['' for _ in range(len(digits))]
def dfs(idx):
if len(digits) == idx:
ans.append(''.join(cur))
return
n = digits[idx]
for c in self.num_letter[n]:
cur[idx] = c
dfs(idx + 1)
dfs(0)
return ans
class Solution:
def expand(self, S: str) -> List[str]:
# 組合題
# 生成所有的組合
if S == 0: return None
options = []
inBrace = False
temp = []
for c in S:
if inBrace and c.isalpha():
temp.append(c)
elif c.isalpha():
temp.append(c)
elif c == "{":
inBrace = True
if not temp: continue
options.append(["".join(temp)])
temp = []
elif c == "}":
inBrace = False
temp.sort()
options.append(temp)
temp = []
if temp: options.append(["".join(temp)])
cur = [''] * len(options)
ans = []
def dfs(idx):
if idx == len(options):
ans.append("".join(cur))
return
for i in options[idx]:
cur[idx] = i
dfs(idx+1)
dfs(0)
return ans
0X01 注意事項(xiàng)
什么時(shí)候使用「組合」
遇到多個(gè)集合之間,元素互相組合的時(shí)候使用組合, 比如我上面的兩道例題
0X02 相關(guān)題目