Letter Combinations of a Phone Number

Jin Shang bio photo By Jin Shang

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.

img

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.

Solution:

Backtrace.

class Solution {
public:
    vector<string> let{
        "", "", "abc", "def", "ghi", "jkl","mno","pqrs","tuv","wxyz"
    };
    vector<string> ans;
    vector<string> letterCombinations(string digits) {
        if(digits.empty()){
            return ans;
        }
        if(ans.empty()){
            ans.push_back("");
        }
        vector<string> t;
        for(char c: let[digits[0]-'0']){
            for(string s: ans){
                t.push_back(s + c);
            }
        }
        ans = t;
        
        return letterCombinations(digits.substr(1, digits.size()-1));
        
    }
};

Iterative Solution:

Remember the index of each solution and add char accordingly (in groups):

len is the current group size, prev length is the previous group size

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        if(digits.empty()){
            return vector<string>();
        }
        int d[10] = {1,1,3,3,3,3,3,4,3,4};
        string l[10] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        int count = 1;
        for(char c : digits){
            count *= d[c-'0'];
        }
        int len = count;
        int prev_len = count;
        vector<string> ans(count,"");
        for(char c: digits){
            len/=d[c-'0'];
            for(int i=0;i<count;i++){
                ans[i]+=l[c-'0'][(i%prev_len)/len];
            }
            prev_len = len;
        }
        return ans;
    }
};