Phone number letter combination

Given a mapping of digits to letters (as in a phone number), and a digit string, return all possible letters the number could represent. You can assume each valid number in the mapping is a single digit.

For example, if {“2”: [“a”, “b”, “c”], 3: [“d”, “e”, “f”], …} then “23” should return [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf"].

Example:

Input:  str ="23"
Output: [ad,ae,af,bd,be,bf,cd,ce,cf]

Approach

C++

#include <bits/stdc++.h>
using namespace std;

vector<stringcombinFunc(vector<stringsvec1string inString)
{
    vector<strings1 = {};
    if (svec1.empty())
    {
        for (int i = 0i < inString.size(); ++i)
        {
            s1.push_back(inString.substr(i1));
        }
        return s1;
    }
    for (int i = 0i < svec1.size(); ++i)
    {
        for (int j = 0j < inString.size(); ++j)
        {
            s1.push_back(svec1[i] + inString[j]);
        }
    }
    return s1;
}
vector<stringletterCombinations(string digits)
{
    map<charstringmyMap = {{'2'"abc"},
                               {'3'"def"},
                               {'4'"ghi"},
                               {'5'"jkl"},
                               {'6'"mno"},
                               {'7'"pqrs"},
                               {'8'"tuv"},
                               {'9'"wxyz"}};
    if (digits.empty())
        return {};
    vector<stringsvec;
    for (int i = 0i < digits.size(); ++i)
    {
        svec.push_back(myMap[digits[i]]);
    }
    vector<stringsol = {};
    for (int i = 0i < svec.size(); ++i)
    {
        sol = combinFunc(solsvec[i]);
    }
    return sol;
}



int main()
{
    string digits = "23";

    vector<stringres = letterCombinations(digits);

    cout << "[";
    for (int i = 0i < res.size(); i++)
    {
        cout << res[i];
        if (i != res.size() - 1)
            cout << ",";
    }
    cout << "]";

    return 0;
}


No comments:

Post a Comment