17. 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.

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.

这道题让我们求电话号码的字母组合, 既2~9中,每个数字都代表2到3个字母,然后给出一个数字的字符串,求出这串数字可能代表的所有字母串.这道题可以用DFS的思想解决,关于DFS可以看二叉树 深度优先搜索(DFS)、广度优先搜索(BFS),可以简单的了解一下.那为什么说是DFS思想呢,比如给出”2345”,那个对应的结果为adgj,adgk,adgl,adhj,adhk,adhl...cfil这个顺序可以看做DFS的思想.大概这个意思.

解法1

解法1就是上面的分析的解法.

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        if (digits.empty()) return res;
        string dict[] = {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        letterCombinationsDFS(digits,dict,0,"",res);
        return res;
    }
    void letterCombinationsDFS(string digits,string dict[],int level,string out,vector<string>& res){
        if (level==digits.size()) res.push_back(out);
        else {
            //找到当前的数字(2~9)对应的stirng("abc"~"wxyz")
            string str = dict[digits[level]-'2'];
            for (int i = 0;i < str.size();i++)
            {
                out.push_back(str[i]);
                letterCombinationsDFS(digits,dict,level+1,out,res);
                out.pop_back();
            }
        }
    }
};

解法2

这个解法就是for循环迭代.循环输入的数字串,每次遇到一个新的数字,将结果数组中的字符串append上新的数字对应的所有字母

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        if (digits.empty()) return res;
        string dict[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        res.push_back("");
        for (int i=0;i<digits.size();i++)
        {
            int n = res.size();
            string str = dict[digits[i]-'2'];
            for (int j = 0; j < n; j++)
            {
                string tmp = res.front();
                res.erase(res.begin());
                for (int k = 0;k<str.size();k++)
                {
                    res.push_back(tmp+str[k]);
                }
            }
        }
        return res;
    }
};
 
comments powered by Disqus