LeetCode算法题——17. Letter Combinations of a Phone Number

来源:互联网 发布:网络维护明细 编辑:程序博客网 时间:2024/06/07 14:04
题目

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.

算法思想:
遍历Digit string,针对Digit string每个字符首先对应到键盘上的字符串,然后让该字符串每个字符加入到字符组合缓存数组里面,更新字符组合缓存结果,然后将组合存入另一个数组中,同时将缓存数组置空。

Python实现如下:

# -*- coding:utf-8 -*-class Solution(object):    def letterCombinations(self, digits):        """        :type digits: str        :rtype: List[str]        """        phone_number=["0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]        ret=[]               digitsLen=digits.__len__()        for i in range(0,digitsLen):            temp=[]     #缓存List            d=digits[i]            s=phone_number[int(d)]   #数字对应字符串            if len(ret)!=0:                         for j in range(0,s.__len__()):                    for k in range(0,len(ret)):                        temp.append(ret[k]+s[j])    #保存暂存List                ret=temp            else:                for k in range(0,s.__len__()):                    ret.append(s[k])          return ret if __name__ == '__main__':    s=Solution()    ress=s.letterCombinations("24")    for i in range(0,len(ress)):        print(ress[i])    


0 0
原创粉丝点击