[LeetCode]Letter Combinations of a Phone Number

时间:2022-09-11 08:20:27

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.

[LeetCode]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.

思考:DFS。

class Solution {
public:
    void DFS(vector<string> &res,string ans,int dep,string digits,string dict[])
    {
        if(dep==digits.size())
        {
            res.push_back(ans);
            return;
        }
        for(int i=0;i<dict[digits[dep]-'0'].size();i++)
        {
            DFS(res,ans+dict[digits[dep]-'0'][i],dep+1,digits,dict);
        }
    }
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        string ans="";
        string dict[]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        DFS(res,ans,0,digits,dict);
        return res;
    }
};