首页 > 代码库 > Leetcode 17. Letter Combinations of a Phone number

Leetcode 17. Letter Combinations of a Phone number

 

求给出的数字串,如果按照电话键盘的编译方式,可以给出多少那些对应的数字组合。例如:

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

 1 class Solution(object):
 2     def letterCombinations(self, digits):
 3         """
 4         :type digits: str
 5         :rtype: List[str]
 6         """
 7         if not digits:
 8             return []
 9         
10         n = len(digits)
11         
12         res = []
13         line = []
14         
15         self.dfs(digits, res, line)
16         
17         return res
18                 
19                 
20     
21     def dfs(self, digits, res, line):
22         if len(digits) == 0:
23             res.append(‘‘.join(line))
24             return 
25         
26         if digits[0] == 2:    
27             self.dfs(digits[1:], res, line+[a])
28             self.dfs(digits[1:], res, line+[b])
29             self.dfs(digits[1:], res, line+[c])
30         if digits[0] == 3:    
31             self.dfs(digits[1:], res, line+[d])
32             self.dfs(digits[1:], res, line+[e])
33             self.dfs(digits[1:], res, line+[f])
34         if digits[0] == 4:    
35             self.dfs(digits[1:], res, line+[g])
36             self.dfs(digits[1:], res, line+[h])
37             self.dfs(digits[1:], res, line+[i])
38         if digits[0] == 5:    
39             self.dfs(digits[1:], res, line+[j])
40             self.dfs(digits[1:], res, line+[k])
41             self.dfs(digits[1:], res, line+[l])
42         if digits[0] == 6:    
43             self.dfs(digits[1:], res, line+[m])
44             self.dfs(digits[1:], res, line+[n])
45             self.dfs(digits[1:], res, line+[o])
46         if digits[0] == 7:    
47             self.dfs(digits[1:], res, line+[p])
48             self.dfs(digits[1:], res, line+[q])
49             self.dfs(digits[1:], res, line+[r])
50             self.dfs(digits[1:], res, line+[s])
51         if digits[0] == 8:    
52             self.dfs(digits[1:], res, line+[t])
53             self.dfs(digits[1:], res, line+[u])
54             self.dfs(digits[1:], res, line+[v])
55         if digits[0] == 9:    
56             self.dfs(digits[1:], res, line+[w])
57             self.dfs(digits[1:], res, line+[x])
58             self.dfs(digits[1:], res, line+[y])
59             self.dfs(digits[1:], res, line+[z])

典型的DFS问题。

Leetcode 17. Letter Combinations of a Phone number