Leetcode 17: Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

Example:

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

这是一道排列组合的题,例子是求[a,b,c]和[d,e,f]的排列组合,有两种方法,一种是递归用DFS做

DFS需要有一个tmp来记录临时结果,用一个index来记录递归到了哪一层,跳出递归条件是递归到最后一层。

class Solution:

    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        num_to_letters = {
            '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"]
        }
        res=[]
        tmp=''
        self.dfs(digits,res,tmp,num_to_letters,0)
        print(res)
    def dfs(self,digits,res,tmp,letters,index):
        if index==len(digits):
            res.append(tmp)
            return
        for i in letters[digits[index]]:
            self.dfs(digits,res,tmp+i,letters,index+1)

还有一种iteration迭代的方法,注意迭代不是简单的嵌套for循环,iteration用了两个数组,一个pre记录之前结果,一个now记录当前结果。首先把第一个数的字母放到now中,然后从第二个数开始遍历,将当前数字对应的字母加入pre中的每一项,如果以23为例的话,每一步的now如下,开始是['a','b','c']

['ad', 'bd', 'cd']
['ad', 'bd', 'cd', 'ae', 'be', 'ce']
['ad', 'bd', 'cd', 'ae', 'be', 'ce', 'af', 'bf', 'cf']

class Solution:

    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        num_to_letters = {
            '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"]
        }

        if not digits:
            return []
        nowlist = num_to_letters[digits[0]]
        prelist = []

        for digit in digits[1:]:
            prelist = nowlist
            nowlist = []
            for letter in num_to_letters[digit]:
                nowlist += [x + letter for x in prelist]
                print(nowlist)
        return nowlist

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值