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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
题解:
class Solution {
public:
static void dfs(map<char, string> dic, string s, int n, vector<string> &ans, int now, string tmp) {
for (int i = 0; i < dic[s[now]].length(); i++) {
tmp += dic[s[now]][i];
if (now == n - 1) {
ans.push_back(tmp);
}
else {
dfs(dic, s, n, ans, now + 1, tmp);
}
tmp.pop_back();
}
}
vector<string> letterCombinations(string digits) {
vector<string> ans;
map<char, string> dic;
string tmp;
dic.insert(pair<char, string>('2', "abc"));
dic.insert(pair<char, string>('3', "def"));
dic.insert(pair<char, string>('4', "ghi"));
dic.insert(pair<char, string>('5', "jkl"));
dic.insert(pair<char, string>('6', "mno"));
dic.insert(pair<char, string>('7', "pqrs"));
dic.insert(pair<char, string>('8', "tuv"));
dic.insert(pair<char, string>('9', "wxyz"));
int n = digits.length();
dfs(dic, digits, n, ans, 0, tmp);
return ans;
}
};