Letter Combinationsofa Phone Number Algorithm

The Letter Combinations of a Phone Number Algorithm is a widely used problem-solving technique in computer programming, which aims to find all possible letter combinations that can be represented by a sequence of digits given on a phone's dial pad. Each digit on the dial pad corresponds to a set of letters, similar to the layout of old-fashioned mobile phones. For example, the digit '2' is associated with the letters 'a', 'b', and 'c', while the digit '3' represents the letters 'd', 'e', and 'f'. The algorithm takes an input of a string of digits and generates a comprehensive list of letter combinations that can be formed using the given digits. This problem is typically solved using recursive techniques or iterative methods such as backtracking or depth-first search (DFS). To implement the algorithm, one needs to first create a mapping of digits to their corresponding letters. Then, using recursion or backtracking, the algorithm generates all the possible letter combinations by exploring every possible combination of the given digits. For each digit, the algorithm iterates through the associated letters, and for each letter, it proceeds to the next digit, repeating the process until all digits have been processed. Once a combination is formed using all the digits, it is added to the result set. This process is repeated for every possible path, ensuring that all valid combinations are discovered. The algorithm efficiently handles cases with varying input lengths and can be easily adapted to accommodate additional characters or symbols on the dial pad, making it a versatile and powerful tool for solving problems related to letter combinations and permutations.
class Solution {
public:
    vector<string> letterCombinations(string digits) {
        map<int, string> keypad;
        keypad[2] = string("abc");
        keypad[3] = string("def");
        keypad[4] = string("ghi");
        keypad[5] = string("jkl");
        keypad[6] = string("mno");
        keypad[7] = string("pqrs");
        keypad[8] = string("tuv");
        keypad[9] = string("wxyz");
        
        vector<string> result;
        string letter;
        dfs(result, letter, digits, 0, keypad);
        return result;
    }
    void dfs(vector<string>& result, string& letter, string& digits, int pos, map<int, string>& keypad) {
        if (pos == digits.size()) {
            result.push_back(letter);
            return;
        }
        int x = digits[pos] - '0';
        string s = keypad[x];
        for (int i = 0; i < s.size(); i++) {
            letter.push_back(s[i]);
            dfs(result, letter, digits, pos + 1, keypad);
            letter.pop_back();
        }
    }
};

LANGUAGE:

DARK MODE: