Letter Combinations of a Phone Number

这个题就是个深度优先遍历DFS,没啥特别的.题目也不难

Letter Combinations of a Phone Number

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

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

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

View Code PYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
    # @return a list of strings, [s1, s2]
    def letterCombinations(self, digits):
        ret = []
        length = len(digits)
        dict = {'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 dfs(num, string, ret):
            if num == length:
                ret.append(string)
                return
            for letter in dict[digits[num]]:
                    dfs(num+1, string+letter, ret)
 
        dfs(0, '', ret)
        return ret

 

Share This: 

Leave a Reply

Your email address will not be published. Required fields are marked *