# 17. 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.

Example 1:

``````**Input:** digits = "23"
``````

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']`.

``````class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.empty()) return {};
vector<string> res;
vector<string> dict{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
dfs(digits, dict, 0, "", res);
return res;
}
void dfs(string digits, vector<string>& dict, int pos, string cur, vector<string>& res) {
if (pos == digits.size()) { res.push_back(cur); return; }
string str = dict[digits[pos] - '0'];
for (int i = 0; i < str.size(); ++i) {
dfs(digits, dict, pos + 1, cur + str[i], res);
}
}
};
``````

``````class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.empty()) return {};
vector<string> res{""};
vector<string> dict{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
for (int i = 0; i < digits.size(); ++i) {
vector<string> t;
string str = dict[digits[i] - '0'];
for (int j = 0; j < str.size(); ++j) {
for (string s : res) t.push_back(s + str[j]);
}
res = t;
}
return res;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/17

Generate Parentheses

Combination Sum

Binary Watch

https://leetcode.com/problems/letter-combinations-of-a-phone-number/

https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/8109/My-recursive-solution-using-Java

https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/8097/My-iterative-sollution-very-simple-under-15-lines

https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/8207/Concise-15-line-Java-Iterative-Solution-very-Straight-Forward-with-Brief-Explanation

LeetCode All in One 题目讲解汇总(持续更新中…)

（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，快快加入吧～）

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation