问题描述
Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.
Example:
Input: “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
解法思路
基本想法是利用map建立一个图,然后利用dfs进行搜索,输出所有的路径
C++代码
void recurseDfs(vector<string>& combos, string curCombo, string& digits, int digitsIdx) {
static const char* phone[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
if (digits.length() == digitsIdx) {
combos.push_back(curCombo);
return;
}
for (const char *letters = phone[digits[digitsIdx]-'0']; *letters != '\0'; ++letters)
recurseDfs(combos, curCombo+*letters, digits, digitsIdx+1);
}
vector<string> letterCombinations(string digits) {
vector<string> combos;
if (digits.length())
recurseDfs(combos, "", digits, 0);
return combos;
}
结果分析
Runtime: 4 ms, faster than 100.00% of C++ online submissions for Letter Combinations of a Phone Number.
Memory Usage: 8.4 MB, less than 99.83% of C++ online submissions for Letter Combinations of a Phone Number.