Leetcode(17)-电话号码的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

思路:其实这个题的逻辑不难,就是要找出对应数字的字母的所有组合。从所有组合这个性质来思考,应该用深度优先搜索的算法。

string dic[10] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
void dfs(string &tmp, int curdep, int depth, vector<string> &ans, string &digits)
{
        if(curdep >= depth)
        {
            ans.push_back(tmp);
            return ;
        }
        for(int i = 0; i < dic[digits[curdep] - '0'].size(); ++ i)
        {
            tmp[curdep] = dic[digits[curdep] - '0'][i];
            dfs(tmp, curdep + 1, depth, ans, digits);
        }
        return ;
}
vector<string> letterCombinations(string digits)
{        
        vector<string> ans;
        if(digits.size() == 0)
            return ans;

        int depth = digits.size();
        string tmp(depth, 0);
        dfs(tmp, 0, depth, ans, digits);
        return ans;
    }

猜你喜欢

转载自www.cnblogs.com/mini-coconut/p/9191058.html