Leetcode 17. Letter Combinations of a Phone number
阿新 • • 發佈:2017-05-14
res bsp self. col join lee num nat leetcode
求給出的數字串,如果按照電話鍵盤的編譯方式,可以給出多少那些對應的數字組合。例如:
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 ifnot 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