您的位置:首页 > 其它

【LeetCode】17. Letter Combinations of a Phone Number 解题报告

2018-02-24 16:26 471 查看

【LeetCode】17. Letter Combinations of a Phone Number 解题报告

标签(空格分隔): LeetCode

题目地址:https://leetcode.com/problems/generate-parentheses/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.

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.

解题方法

依然是回溯法。要求所有的可能的字符串的组合。

有点类似784. Letter Case Permutation,不需要对index进行for循环,因为对index进行for循环产生的是所有可能的组合。而这两个题要求的组合的长度是固定的,每个位置都要有字母。

另外就是要判断一下
path != ''
,原因是当digits为”“的要求的结果是[],而不是[“”]。

class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
kvmaps = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
res = []
self.dfs(digits, 0, res, '', kvmaps)
return res

def dfs(self, string, index, res, path, kvmaps):
if index == len(string):
if path != '':
res.append(path)
return
for j in kvmaps[string[index]]:
self.dfs(string, index + 1, res, path + j, kvmaps)


方法二:

使用python 自带的product笛卡尔乘积函数。

from itertools import product
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if not digits:
return []
kvmaps = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
answer = []
for each in product(*[kvmaps[key] for key in digits]):
answer.append(''.join(each))
return answer


Date

2018 年 2 月 24 日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: