17. Letter Combinations of a Phone Number

1. Description

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 digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Leetcode 17

2. Example

Example 1:
Input: digits = “23”
Output: [“ad”,“ae”,“af”,“bd”,“be”,“bf”,“cd”,“ce”,“cf”]

Example 2:
Input: digits = ""
Output: []

Example 3:
Input: digits = “2”
Output: [“a”,“b”,“c”]

3. Constraints

  • 0 <= digits.length <= 4
  • digits[i] is a digit in the range [‘2’, ‘9’].

4. Solutions

My Accepted Solution

m is the number of digits in i_digits, which has 3 letters, n is the number of digits having 4 letters
Time complexity: O($3^m4^n$)
Space complexity: O($3^m4^n$)

class Solution {
public:
    vector<string> letterCombinations(const string &digits) {
        if(digits.empty()) {
            return {};
        }

        string combination;
        generate_combinations(0, digits, combination);

        return combinations;
    }

private:
    vector<string> combinations;
    unordered_map<char, vector<char>> digit_letters = {
            {'2', {'a', 'b', 'c'}},
            {'3', {'d', 'e', 'f'}},
            {'4', {'g', 'h', 'i'}},
            {'5', {'j', 'k', 'l'}},
            {'6', {'m', 'n', 'o'}},
            {'7', {'p', 'q', 'r', 's'}},
            {'8', {'t', 'u', 'v'}},
            {'9', {'w', 'x', 'y', 'z'}},
        };

    void generate_combinations(int index, const string &digits, string &m_combination) {
        if(index == digits.size()) {
            combinations.emplace_back(m_combination);
        } else {
            for(auto letter : digit_letters[digits[index]]) {
                m_combination.push_back(letter);
                generate_combinations(index + 1, digits, m_combination);
                m_combination.pop_back();
            }
        }
    }
};
comments powered by Disqus