sjw_blog


  • 首页

  • 关于

  • 标签

  • 分类

  • 归档

Letter Combinations of a Phone Number

发表于 2018-02-02 | 分类于 Leetcode

[Leetcode]Letter Combinations of a Phone Number

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.
phonenum

1
2
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.

解题思路:
使用backtracking,从后往前将所有的手机号码对应的字母返回给前一个号码,将其组合获得结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
kvmaps = {'1': '*',
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz',
'0': ' '
}
class Solution(object):

def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if digits == "":
return []
combinations = []
if len(digits) == 1:
for x in kvmaps[digits[0]]:
combinations.append(x)
else:
for c in self.letterCombinations(digits[1:]):
for x in kvmaps[digits[0]]:
combinations.append(x + c)
return combinations

postName

发表于 2018-02-02

Hello World

发表于 2018-02-02

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1
$ hexo new "My New Post"

More info: Writing

Run server

1
$ hexo server

More info: Server

Generate static files

1
$ hexo generate

More info: Generating

Deploy to remote sites

1
$ hexo deploy

More info: Deployment

1…56

sujunwei

53 日志
5 分类
11 标签
© 2018 true
由 Hexo 强力驱动
|
主题 — NexT.Pisces v5.1.4