题目
Given a digit string, 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.
boke_0.pngInput: Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
频度: 3
解题之法
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> res;
if (digits.empty()) return res;
string dict[] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
letterCombinationsDFS(digits, dict, 0, "", res);
return res;
}
void letterCombinationsDFS(string digits, string dict[], int level, string out, vector<string> &res) {
if (level == digits.size()) res.push_back(out); //level 记录当前生成的字符串的字符个数
else {
string str = dict[digits[level] - '0'];
for (int i = 0; i < str.size(); ++i) {
out.push_back(str[i]);
letterCombinationsDFS(digits, dict, level + 1, out, res);
out.pop_back();
}
}
}
};
网友评论