17. Letter Combinations of a Phone Number

Given a digit string excluded 0 and 1, 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.
| 1 | 2 ABC | 3 DEF |
|---|---|---|
| 4 GHI | 5 JKL | 6 MNO |
| 7 PQRS | 8 TUV | 9 WXYZ |
Example
Example 1:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
Explanation:
'2' could be 'a', 'b' or 'c'
'3' could be 'd', 'e' or 'f'
Example 2:
Input: "5"
Output: ["j", "k", "l"]Notice
Although the answer above is in lexicographical order, your answer could be in any order you want.
- class Solution {
- private:
- const vector<string> KEYBOARD {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
- public:
- vector<string> letterCombinations(string digits) {
- int size = digits.length();
- if (size == 0) return {};
- vector<string> result;
- dfs(digits, 0, "", result);
- return result;
- }
- void dfs(const string &digits, int index, string path, vector<string> &result) {
- if (index == digits.size()) {
- result.push_back(path);
- return;
- }
- for (auto c: KEYBOARD[digits[index] - '0']) {
- dfs(digits, index + 1, path + c, result);
- }
- }
- };
Note:
vector vs {}
Comments
Post a Comment