class Solution:
def __init__(self):
self.ans = list()
self.digits = None
self.digitLetterMapping = {
'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 letterCombinations(self, digits: str) -> List[str]:
n = len(digits)
if n == 0:
return []
self.digits = digits
self.DFS(0, n, '')
return self.ans
def DFS(self, i, n, letterSoFar):
if i == n:
self.ans.append(letterSoFar)
return
for l in self.digitLetterMapping[self.digits[i]]:
self.DFS(i + 1, n, letterSoFar + l)
itertools.product(*iterables, repeat=1)
입력 이터러블들(iterables)의 데카르트 곱(Cartesian product, 곱집합).
import itertools
def letterCombinations(self, digits: str) -> List[str]:
if len(digits) == 0:
return []
# Each digit map to an interator. (Recall strings are iterators)
buttons = {'2':'abc','3':'def','4': 'ghi',\
'5':'jlk','6':'mno','7':'pqrs',\
'8':'tuv','9':'wxyz'}
iterators = [buttons[d] for d in digits]
# itertools.product(*args) returns the Cartesian product of the input iterables.
return [''.join(x) for x in itertools.product(*iterators)]
itertools.product() - 문서