17. Letter Combinations of a Phone Number

https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
题目大意:给一串数,每个数字对应手机键盘上的几个字母,求数字对应字母的笛卡尔积。

解题思路:用迭代法。如“23”,2对应“abc”,3对应“def”,对每个数字进行遍历。初始结果集为空(用一个空串""表示),
第一轮,i=0,候选集为digits[0]=2,即abc。每轮对结果集的每个元素(此时为唯一元素"")分别添加候选集的每个元素’a’,’b’,’c’,得到新的结果替换原来的结果集,此时结果集=[‘a’,’b’,’c’]
第二轮,i=1,候选集为digits[1]=3,即def。对结果集的每个元素(此时为’a’,’b’,’c’),分别添加候选集的每个元素’d’,’e’,’f’,共得到3*3=9种新结果:
[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”],替换原结果集。
以此类推,迭代到最后。

class Solution:
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        if not digits: return []
        res = [""]  #初始结果集,有一个空串元素
        v = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
        for i in range(len(digits)):  #对每位数字
            dig = int(digits[i])  #先将字符串转为整数
            candidate = v[dig]  #候选集
            newRes = []  #新结果集,初始为空
            for j in res:
                for k in candidate:
                    newRes.append(j + k)  #候选集每个元素添加到原结果后面,得到新结果
            res = newRes
        return res

思路2:用python的itertools.product()方法生成笛卡尔积。
这个方法的用法如下:输入参数为可变:

for s in itertools.product('abc', 'def'):
    print(s)

输出’abc’, ‘def’的笛卡尔积:
(‘a’, ‘d’)
(‘a’, ‘e’)
(‘a’, ‘f’)
(‘b’, ‘d’)
(‘b’, ‘e’)
(‘b’, ‘f’)
(‘c’, ‘d’)
(‘c’, ‘e’)
(‘c’, ‘f’)

class Solution:
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        if not digits: return []
        res = []
        letters = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]  #将所有数字对应的字符分别存入
        return ["".join(s) for s in itertools.product(*[letters[int(dig)] for dig in digits])]

最后return写的较复杂,拆开分析:
首先返回的是一个list。其中有一个空串,每次用空串的join方法写入字符串s。
s是笛卡尔积的结果,笛卡尔积输入的参数是一个解包(py3.5新特性),用for循环将所有串输入。
注意这个*号,是解包的意思,即将列表[]中的参数一个个取出来,否则就是将整个list作为函数的输入。对比下面两段代码:

return ["".join(s) for s in itertools.product(*['abc', 'def'])]

返回[‘ad’, ‘ae’, ‘af’, ‘bd’, ‘be’, ‘bf’, ‘cd’, ‘ce’, ‘cf’]

return ["".join(s) for s in itertools.product(['abc', 'def'])]

返回[‘abc’, ‘def’],一个元素的笛卡尔积等于自身

注意另一个点,[]中嵌套for表达式称为列表推导式,形式如下:

[表达式 for 变量 in 列表]    或者  [表达式 for 变量 in 列表 if 条件]

因为需要对所有digits遍历,需要用到列表推导式,而推导式本身又是一个list[],因此需要用到解包*。环环相扣。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
(Telephone Number Word Generator) Standard telephone keypads contain the digits 0 through 9. The numbers 2 through 9 each have three letters associated with them, as is indicated by the following table: Many people find it difficult to memorize phone numbers, so they use the correspondence between digits and letters to develop seven-letter words that correspond to their phone numbers. For example, a person whose telephone number is 686-2377 might use the correspondence indi- cated in the above table to develop the seven-letter word “NUMBERS.” Businesses frequently attempt to get telephone numbers that are easy for their clients to remember. If a business can advertise a simple word for its customers to dial, then no doubt the business will receive a few more calls. Each seven-letter word corresponds to exactly one seven-digit telephone number. The restaurant wishing to increase its take-home business could surely do so with the number 825-3688 (i.e., “TAKEOUT”). Each seven-digit phone number corresponds to many separate seven-letter words. Unfortunately, most of these represent unrecognizable juxtaposi- tions of letters. It’s possible, however, that the owner of a barber shop would be pleased to know that the shop’s telephone number, 424-7288, corresponds to “HAIRCUT.” A veterinarian with the phone number 738-2273 would be happy to know that the number corresponds to “PETCARE.” Write a program that, given a seven-digit number, writes to a file every possible seven-letter word corresponding to that number. There are 2187 (3 to the seventh power) such words. Avoid phone numbers with the digits 0 and 1.
最新发布
06-09

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值