Letter Combinations of a Phone Number

Given a digit string, 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.

Letter Combinations of a Phone Number

Input:Digit string "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.

class Solution {
public:
    vector<string> ans;
    unordered_map<char,string> um;
    void dfs(string digits,vector<char> path, int pos){
        if (pos == digits.size()){
            string s;
            for(int i = 0; i < path.size();i++) s += path[i];
            ans.push_back(s);
            return;
        }
        string v = um[digits[pos]];
        for(int i = 0; i < v.size();i++){
            path.push_back(v[i]);
            dfs(digits,path,pos+1);
            path.resize(path.size() -1);
        }
    }
    vector<string> letterCombinations(string digits) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        um.insert(make_pair('2',"abc"));
        um.insert(make_pair('3',"def"));
        um.insert(make_pair('4',"ghi"));
        um.insert(make_pair('5',"jkl"));
        um.insert(make_pair('6',"mno"));
        um.insert(make_pair('7',"pqrs"));
        um.insert(make_pair('8',"tuv"));
        um.insert(make_pair('9',"wxyz"));
        vector<char> path;
        ans.clear();
        dfs(digits,path,0);
        return ans;
    }
};

原文链接: https://www.cnblogs.com/kwill/p/3189807.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/95832

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月10日 上午3:17
下一篇 2023年2月10日 上午3:17

相关推荐