letter combinations of a phone number

还是不明白为何当初没做出来,也许是头昏了吧,很直接了当的一道backtracking题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class (object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if not digits:
return []
int2chr = {1: "*", 2: "abc", 3: "def", 4: "ghi", 5: "jkl", 6: "mno", 7: "pqrs", 8: "tuv", 9: "wxyz"}
res = []
self.dfs(digits, 0, [], int2chr, res)
return res
def dfs(self, digits, pos, cur, int2chr, res):
if pos == len(digits):
res.append("".join(cur))
return
l = int2chr[int(digits[pos])]
for i in range(len(l)):
cur.append(l[i])
self.dfs(digits, pos+1, cur, int2chr, res)
cur.pop()