[leetcode题解]17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

Example:

Input: "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 的字母串,要求计算所有它能表示的字母序组合然后返回。

给出数字到字母的映射关系如下(与手机按键上字母相同)。caution: 1 不对应任何字母。

示例:

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

说明:
虽然上面给出的答案是以字典序排列的,但是这不是强制性的要求,可以按照任何顺序输出答案。

题目其实考察的是搜索算法,也可以很容易的看出是深度优先搜索,找出所有从最上层到最下层的路径,每个字母是一层,所以,我们可以写一个dfx搜索算法,递归的去做就好了。

首先要遍历每一层,对于每一层,以每个字母作为根节点,然后去找从当前节点网下走,所有能走到的叶子节点,叶子节点就是最后一个字母(最后一层)所包含的节点。因为是最后一层,所以,他的下一层也就是i+1就会到达层高,这时候就表明一条路径已经完成。整体来说相当简单。代码如下:

class Solution {
private:
    void dfs(string &digits, int idx, string &s, vector<string> &res) {
        int i = 0;
        string tmp = "";
        
        if (idx >= digits.length()) {
            res.push_back(s);
            return;
        }
        
        tmp = map[digits[idx] - '0'];
        for (i = 0; i < tmp.length(); i++) {
            s.push_back(tmp[i]);
            dfs(digits, idx + 1, s, res);
            s.pop_back();
        }
    }
    
    string map[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        string s = "";
        
        if (digits.length() == 0)
            return res;
        
        dfs(digits, 0, s, res);
        return res;
    }
};

本文遵从CC3.0协议转载请注明:转自凌风技术站

本文标题:[leetcode题解]17. Letter Combinations of a Phone Number

本文链接地址:https://www.iaccepted.net/algorithm/leetcode/202.html

相关文章