算法分析与设计课程(2):Letter Combinations of a Phone Number
2017-03-03 15:41
267 查看
Description:
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.
算法思路:这种情况下很容易想到用递归的方法。
将字串的第一个字符和其他字符看成两个部分,用第一个字符产生字符串,连接上其余部分的字符串,即可枚举所有的组合
代码如下:
运行结果如下图:
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"].
算法思路:这种情况下很容易想到用递归的方法。
将字串的第一个字符和其他字符看成两个部分,用第一个字符产生字符串,连接上其余部分的字符串,即可枚举所有的组合
代码如下:
__author__ = 'andy' class Solution(object): def letterCombinations(self, digits): dicLetter = {0:' ',1:'',2:'abc',3:'def',4:'ghi',5:'jkl',6:'mno',7:'pqrs',8:'tuv',9:'wxyz'} length = len(digits) if length == 0: return [] intIndex = int(digits[0]) result = [] arr = [] #第一个字符 letter = dicLetter[intIndex] for l in letter: if length > 1: #其他的字符 arr =self.letterCombinations(digits[1:]) for m in arr: result.append(l+m) else: result.append(l) return result case = Solution() print(case.letterCombinations("23"))
运行结果如下图:
相关文章推荐
- 算法分析与设计——LeetCode Problem.17 Letter Combinations of a Phone Number
- 算法系列——Letter Combinations of a Phone Number
- 广度优先遍历算法求解 Letter Combinations of a Phone Number
- 每日一道算法题——Letter Combinations of a Phone Number
- 深度优先遍历算法求解 Letter Combinations of a Phone Number
- LeetCode OJ算法题(十八):Letter Combinations of a Phone Number
- LeetCode - Letter Combinations of a Phone Number
- LeetCode_Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- LeetCode 17: Letter Combinations of a Phone Number
- [LeetCode]Letter Combinations of a Phone Number
- LeetCode Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- [leetcode]Letter Combinations of a Phone Number
- Leetcode Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- LeetCode: "Letter Combinations of a Phone Number
- leetcode -- Letter Combinations of a Phone Number