How to get all letter combinations of a phone number given a string of digits from 2-9 in C++

1 Answer

0 votes
#include <iostream>
#include <vector>

// Letter Combinations of a Phone Number
// Given a string containing digits from 2-9, 
// get all possible letter combinations that a phone number represent

class Program {
public:
    //                                  2      3      4      5      6      7       8      9
    std::vector<std::string> letters {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    std::vector<std::string> result;
    
    void printVector(std::vector<std::string> const &v) {
        for (auto const &n: v) {
            std::cout << n << " ";
        }
    }

    void CreateCombinations(std::string digits, std::string output, int di) {
        if (digits.size() == di) {
            result.push_back(output);
            return;
        }
        
        //for (int i = 0; i < letters[digits[di] - 50].size(); i++) {
            // 50 = 48('0') + 2 for letters index. 2->0 3->1 ('2' - 48('0') = 2 - 2 = 0 (index 0)
        for (int i = 0; i < letters[digits[di] - '2'].size(); i++) {
            //output.push_back(letters[digits[di] - 50][i]);
            output.push_back(letters[digits[di] - '2'][i]);
            // '2' for letters index. 2->0 3->1 ('2' - 48('0') = 2 - 2 = 0 (index 0)
            CreateCombinations(digits, output, di + 1);
            output.pop_back();
        }
    }
    
    std::vector<std::string> LetterCombinationsOfPhoneNumber(std::string digits) {
        if (digits == "") {
            return result;
        }
        
        std::string output;
        
        CreateCombinations(digits, output, 0);
        
        return result;
    }
};

int main() {
    Program p;
    
    std::vector<std::string> result = p.LetterCombinationsOfPhoneNumber("23");
    
    p.printVector(result);
}


/*
run:

ad ae af bd be bf cd ce cf

*/

 



answered Mar 4, 2024 by avibootz
edited Mar 4, 2024 by avibootz
...