In the Leetcode Letter Combinations of a Phone Number problem solution in C++ programming 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.
Leetcode Letter Combinations of a Phone Number problem solution in C++ programming
class Solution {
public:
vector<string> dfs(string digits) {
vector<string> ret;
if(digits == "") return ret;
map<char, string> mp;
mp['2'] = "abc";
mp['3'] = "def";
mp['4'] = "ghi";
mp['5'] = "jkl";
mp['6'] = "mno";
mp['7'] = "pqrs";
mp['8'] = "tuv";
mp['9'] = "wxyz";
char first = digits[0];
string others = digits.substr(1);
for(int i = 0; i < mp[first].length(); i++) {
if(others != "") {
vector<string> v = dfs(others);
for(int j = 0; j < v.size(); j++) {
ret.push_back(mp[first][i] + v[j]);
}
} else {
string s(1, mp[first][i]);
ret.push_back(s);
}
}
return ret;
}
vector<string> letterCombinations(string digits) {
vector<string> ret = dfs(digits);
return ret;
}
};
Also read,
- Leetcode Letter Combinations of a Phone Number problem solution in C
- Leetcode Letter Combinations of a Phone Number problem solution in Java
- Leetcode Letter Combinations of a Phone Number problem solution in Python
- Leetcode Letter Combinations of a Phone Number problem solution in C#