LeetCode_17. Monogram phone number

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/all_about_WZY/article/details/102659368

Subject description:

Given a string contains only numeric characters 2-9, it can return all letter combinations indicated.
Given digital map to letters as follows (the same telephone key). Note 1 does not correspond to any alphabet.
Here Insert Picture Description

Example:

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

Algorithm thinking: This topic can be solved by DFS and BFS two ways.
DFS is used mainly back method, first of all been traversed digits of numbers, and then add the path to the res obtained, and then back to the previous figures.
BFS uses a queue, all the results stored layer by layer

//DFS
class Solution {
public:
    void DFS(string digits,int pos,string &path,vector<string>& res,vector<string>& dic){
        if(pos==digits.size()){
            res.push_back(path);
            return;
        }
        for(auto c:dic[digits[pos]-'0']){
            path.push_back(c);
            DFS(digits,pos+1,path,res,dic);
            path.pop_back();
        }
    }
    
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        string path="";
        if(digits.empty())
            return res;
        vector<string> dic={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        DFS(digits,0,path,res,dic);
        return res;
    }
};

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/all_about_WZY/article/details/102659368