[Leetcode]Letter Combinations of a Phone Number

来源:互联网 发布:消防海湾主机编程实例 编辑:程序博客网 时间:2024/04/29 16:35

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.

给定一串数字,求出在电话按键中可能得到的字母组合~可以用DFS来做,维护一个数组digitToLetters,表示每个数字对应代表的字母~

class Solution:    # @return a list of strings, [s1, s2]    def letterCombinations(self, digits):        if digits is None or len(digits) == 0:            return [""]        self.res = []        self.digitToLetters = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]        self.helper(digits, 0, [])        return self.res            def helper(self, digits, index, item):        if len(digits) == index:            self.res.append(''.join(item))            return        for c in self.digitToLetters[int(digits[index])]:            item.append(c)            self.helper(digits, index + 1, item)            item.pop()
还有非递归解法,依次读取数字,然后把数字可以代表的字符依次加到当前的所有结果中,然后进入下一次迭代,代码如下~

class Solution:    # @return a list of strings, [s1, s2]    def letterCombinations(self, digits):        if digits is None or len(digits) == 0:            return [""]        res = [""]        digitToLetters = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]        for i in xrange(len(digits)):            newRes = []            for c in digitToLetters[int(digits[i])]:                for j in xrange(len(res)):                    newRes.append(res[j] + c)            res = newRes        return res



0 0
原创粉丝点击