LeetCode Medium: 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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
给定一个数字串,每一个数字所代表的的与电话号码上的一样,对每一个数字代表的字符进行组合。
二、思路
递归或者迭代,每迭代一哥 新的字符,就应该在上一次结果的基础上进行组合。下面给出三种不同的方式写的代码,思想都是一样。这些代码分别来自三个不同的博客,后面有附。
三、代码
#coding:utf-8 class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if digits == '': return [] self.DigitDict=[' ','1', "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] res = [''] for d in digits: res = self.letterCombBT(int(d),res) print(res) return res def letterCombBT(self, digit, oldStrList): return [dstr+i for i in self.DigitDict[digit] for dstr in oldStrList] class Solution1(object): def letterCombinations1(self, digits): """ :type digits: str :rtype: List[str] """ digits = digits.strip() if len(digits)==0: return [] rtn_queue=[""] head_ind=0 # the head of queue head_ele="" # the head element of queue mapping= ["0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] dig_ind=0 for dig in digits: x = int(dig) while len(rtn_queue[head_ind])==dig_ind: head_ele=rtn_queue[head_ind] head_ind+=1 for ch in mapping[x]: rtn_queue.append(head_ele+ch) dig_ind+=1 queue_n = len(rtn_queue) print(rtn_queue[head_ind:queue_n]) return rtn_queue[head_ind:queue_n] class Solution2: map=[" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] length=0;res=[] # @param {string} digits # @return {string[]} def letterCombinations2(self, digits): self.length=len(digits) self.res=[] if self.length==0:return self.res; tmp=['' for i in range(self.length)] self.getLetterCom(0,digits,tmp) print(self.res) return self.res def getLetterCom(self,index,digits,tmp): if index>=self.length: letters=''.join(tmp) self.res.append(letters) return digit=ord(digits[index])-ord('0') for i in range(len(self.map[digit])): tmp[index]=self.map[digit][i] self.getLetterCom(index+1,digits,tmp) if __name__ == '__main__': import time a = "23" start = time.clock() ss = Solution() ss.letterCombinations(a) end = time.clock() cost = end - start print(cost) start1 = time.clock() ss1 = Solution1() ss1.letterCombinations1(a) end1 = time.clock() print(end1 - start1) ss2 = Solution2() ss2.letterCombinations2(a)
参考博客:https://blog.csdn.net/zl87758539/article/details/51675166 https://blog.csdn.net/daigualu/article/details/74091229 https://blog.csdn.net/runningtortoises/article/details/45620177
既然无论如何时间都会过去,为什么不选择做些有意义的事情呢