17. Letter Combinations of a Phone Number

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.

vector<string> letterCombinations(string digits) { // time: O(4^n); space: O(4^n)
    vector<string> res;
    if (digits.empty()) return res;
    vector<string> letters = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    string cur;
    helper(digits, letters, res, cur, 0);
    return res;
}
void helper(string& digits, vector<string>& letters, vector<string>& res, string& cur, int idx) {
    if (idx == digits.size()) {
        res.push_back(cur);
    } else {
        string letter = letters[digits[idx] - '0'];
        for (int i = 0; i < letter.size(); ++i) {
            cur.push_back(letter[i]);
            helper(digits, letters, res, cur, idx + 1);
            cur.pop_back();
        }
    }
}
vector<string> letterCombinations(string digits) { // time: O(4^n); space: O(4^n)
    vector<string> res;
    if (digits.empty()) return res;
    res.push_back({});
    vector<string> letters = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    for (int i = 0; i < digits.size(); ++i) {
        string letter = letters[digits[i] - '0'];
        vector<string> t;
        for (int j = 0; j < letter.size(); ++j) {
            for (string& s : res)
                t.push_back(s + letter[j]);
        }
        res = t;
    }
    return res;
}

Last updated

Was this helpful?