Fork me on GitHub

Leetcode17.Letter Combinations of a Phone Number电话号码的字母组合

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

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

示例:

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

说明:

尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。

 

搜索回溯

 

class Solution {
public:
    vector<string> res;
    vector<vector<char> > hash;
    vector<string> letterCombinations(string digits)
    {
        int len = digits.size();
        if(len == 0)
            return res;
        hash = vector<vector<char> >(10, vector<char>(5, 0));
        int cnt = 0;
        for(int i = 2; i <= 9; i++)
        {
            int boundary;
            if(i == 7 || i == 9)
                boundary = 4;
            else
                boundary = 3;
            for(int j = 0; j < boundary; j++)
            {
                hash[i][j] = cnt + 'a';
                cnt++;
            }
        }
        DFS(0, "", digits);
        return res;
    }

    void DFS(int cnt, string str, string digits)
    {
        if(cnt == digits.size())
        {
            res.push_back(str);
            return;
        }
        int x = digits[cnt] - '0';
        for(int i = 0; i < hash[x].size(); i++)
        {
            if(hash[x][i] == 0)
                break;
            char temp = hash[x][i];
            DFS(cnt + 1, str + temp, digits);
        }
    }
};

posted @ 2018-11-17 18:49  lMonster81  阅读(109)  评论(0编辑  收藏  举报
/*评论*/ /*top按钮*/

/* 网易云控件 */