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"].
class Solution { void dfs(string mp[10], string& digits, int cur, vector<string>& ans, string path, bool vis[10][4]) { if(cur == digits.size()) { if(path.size() > 0) ans.push_back(path); return ; } int digit = digits[cur]-'0'; string s = mp[digit]; int n = s.size(); for(int i=0; i<n; i++) { if(vis[cur][i]) continue; vis[cur][i] = true; path.push_back(s[i]); dfs(mp, digits, cur+1, ans, path, vis); vis[cur][i] = false; path.pop_back(); } } public: vector<string> letterCombinations(string digits) { string mp[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; vector<string> ans; bool vis[10][4] = {false}; dfs(mp, digits, 0, ans, "", vis); return ans; } };