Leetcode Study Day 48

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. Return the answer in any order.

A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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"]


Constraints:

0 <= digits.length <= 4
digits[i] is a digit in the range ['2', '9'].

My solution

My solution is to use a recursive function with index as the parameter. When the index is equal to the length of the digits, we append the current string to the result. Otherwise, we loop through the letters of the current digit and call the recursive function with the next index.

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
30
31
32
33
class Solution {
public:
vector<string> ans;
unordered_map <char, vector<char>> numLetter;

void recursion(string current, int index, string digits){
if (index == digits.size()){
ans.push_back(current);
return;
}
else{
for(int i = 0; i< numLetter[digits[index]].size(); i++){
current += numLetter[digits[index]][i];
recursion(current, index+1, digits);
current.pop_back();
}
}
}
vector<string> letterCombinations(string digits) {
if (digits == "") return ans;
string current = "";
numLetter['2'] = {'a', 'b', 'c'};
numLetter['3'] = {'d', 'e', 'f'};
numLetter['4'] = {'g', 'h', 'i'};
numLetter['5'] = {'j', 'k', 'l'};
numLetter['6'] = {'m', 'n', 'o'};
numLetter['7'] = {'p', 'q', 'r','s'};
numLetter['8'] = {'t', 'u', 'v'};
numLetter['9'] = {'w', 'x', 'y', 'z'};
recursion(current, 0, digits);
return ans;
}
};
  • Copyrights © 2020-2024 Yangyang Cui

请我喝杯咖啡吧~

支付宝
微信