当前位置:网站首页>Leetcode: 17. letter combination of phone number
Leetcode: 17. letter combination of phone number
2022-07-23 14:56:00 【uncle_ ll】
17. Letter combination of telephone number
source : Power button (LeetCode)
link : https://leetcode.cn/problems/letter-combinations-of-a-phone-number/
Given a number only 2-9 String , Returns all the letter combinations it can represent . You can press In any order return .
The mapping of numbers to letters is given as follows ( Same as phone key ). Be careful 1 Does not correspond to any letter .

Example 1:
Input :digits = "23"
Output :["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input :digits = ""
Output :[]
Example 3:
Input :digits = "2"
Output :["a","b","c"]
Tips :
0 <= digits.length <= 4
digits[i] Is the scope of ['2', '9'] A number of .
solution
- recursive : If digits The length of is equal to 1, Map to string and convert to list ; If the length is greater than 1 Words , Recursion first n-1 The result of length , The last number is mapped ; Write a double loop to combine .
- to flash back : First, build a hash table to represent the phone number disk , Then based on digits Go back , The string is initially empty . Take one digit of the phone number at a time , Get all possible letters corresponding to the number from the hash table , And insert one of the letters after the existing alphabet , Then continue to process the last digit of the phone number , Until all the numbers in the phone number are processed , That is to get a complete alphabetic arrangement . And then go back , Traverse the rest of the alphabet .
Code implementation
recursive
python Realization
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits or len(digits) == 0:
return []
mapping = {
'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
'6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
if len(digits) == 1:
return list(mapping[digits[0]])
prev_letters = self.letterCombinations(digits[:-1])
reverse_letter = mapping[digits[-1]]
return [s + c for s in prev_letters for c in reverse_letter]
c++ Realization
class Solution {
public:
vector<string> letterCombinations(string digits) {
int n = digits.size();
if (n == 0) return {
};
unordered_map<char, string> maps {
{
'2', "abc"},
{
'3', "def"},
{
'4', "ghi"},
{
'5', "jkl"},
{
'6', "mno"},
{
'7', "pqrs"},
{
'8', "tuv"},
{
'9', "wxyz"}
};
vector<string> res;
if (n == 1) {
string letter = maps[digits[0]];
for (char ch: letter) {
string s;
res.push_back(s+ch);
}
return res;
}
string digits2 = digits.substr(0, n-1);
vector<string> prev_letters = letterCombinations(digits2);
string letter = maps[digits[n-1]];
for (auto prev_letter: prev_letters) {
for (char ch: letter) {
res.push_back(prev_letter+ch);
}
}
return res;
}
};
Complexity analysis
- Time complexity : O ( 3 m + 4 n ) O(3^m+4^n) O(3m+4n) m It's corresponding to 3 Alphanumeric number ,n It's corresponding to 4 The number of alphanumeric , There are different combinations of letters 3 m × 4 n 3^m \times 4^n 3m×4n Kind of , You need to traverse every letter combination .
- Spatial complexity : O ( m + n ) O(m+n) O(m+n)
to flash back
python Realization
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits or len(digits) == 0:
return []
letters = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
res = []
n = len(digits)
def helper(path, depth):
if depth == n:
res.append(''.join(path))
return
string = letters[digits[depth]]
for ch in string:
path.append(ch)
helper(path, depth+1)
path.pop()
helper([], 0)
return res
c++ Realization
class Solution {
vector<string> res;
unordered_map<char, string> maps {
{
'2', "abc"},
{
'3', "def"},
{
'4', "ghi"},
{
'5', "jkl"},
{
'6', "mno"},
{
'7', "pqrs"},
{
'8', "tuv"},
{
'9', "wxyz"}
};
public:
void helper(vector<char> path, int depth, string digits,vector<string>& res, unordered_map<char, string> maps) {
if (depth == digits.size()) {
string tmp;
for (auto ch: path) {
tmp += ch;
}
res.push_back(tmp);
return ;
}
string letters = maps[digits[depth]];
for (int i=0; i<letters.size(); i++) {
char ch = letters[i];
path.push_back(ch);
helper(path, depth+1, digits, res, maps);
path.pop_back();
}
}
vector<string> letterCombinations(string digits) {
if (digits.size() == 0)
return {
};
helper({
}, 0, digits, res, maps);
return res;
}
};
Complexity analysis
- Time complexity : O ( 3 m + 4 n ) O(3^m+4^n) O(3m+4n) m It's corresponding to 3 Alphanumeric number ,n It's corresponding to 4 The number of alphanumeric , There are different combinations of letters 3 m × 4 n 3^m \times 4^n 3m×4n Kind of , You need to traverse every letter combination .
- Spatial complexity : O ( m + n ) O(m+n) O(m+n)
Reference resources
边栏推荐
- Common JS modular specification from a code question
- 生成订单号
- Building personal network disk based on nextcloud
- [array & String & Macro exercise]
- [applet automation minium] III. element positioning - use of wxss selector
- [test platform development] XVII. The interface editing page realizes the drop-down cascade selection, and binds the module to which the interface belongs
- Due to resource constraints, the namenode fails to start with an error unable to create new native thread
- Dynamic programming -- knapsack problem
- Map structure stored in the room of jetpack series
- 身份证号正则验证
猜你喜欢

The pit trodden by real people tells you to avoid the 10 mistakes often made in automated testing

【面试高频】cookie、session、token?看完再也不担心被问了

About flex layout justify content: the last solution to the misalignment of space around and why it is solved like this is a discussion

supervisord安装使用

R language practical application case: drawing part (III) - drawing of multiple combination patterns

【测试平台开发】23. 接口断言功能-保存接口断言和编辑回显

Advanced operation and maintenance 02

@FeignClient使用詳細教程(圖解)

Kettle implémente une connexion de base de données partagée et insère une instance de composant de mise à jour

直播课堂系统03补充-model类及实体
随机推荐
Redis | 非常重要的中间件
C thread lock and single multithreading are simple to use
Quick introduction to PKI system
Qt| imitation text floating letter
mysql函数汇总之字符串函数
C language introduction practice (11): enter a group of positive integers and sum the numbers in reverse order
Official wechat product! Applet automation framework minium sharing Preview
Feignclient utilise un tutoriel détaillé (illustration)
基本51单片机点阵汉字显示程序设计
4. Find the median of two positive arrays
[record of question brushing] 19. Delete the penultimate node of the linked list
Dynamic programming -- knapsack problem
Live classroom system 01 database table design
[software test] redis abnormal test encountered in disk-to-disk work
Yunna - how to strengthen fixed asset management? How to strengthen the management of fixed assets?
【测试平台开发】23. 接口断言功能-保存接口断言和编辑回显
Educational Codeforces Round 132 (Rated for Div. 2) D. Rorororobot
【小程序自动化Minium】一、框架介绍和环境搭建
Common JS modular specification from a code question
mysql 之general_log日志