其他分享
首页 > 其他分享> > LeetCode 17. 电话号码的字母组合

LeetCode 17. 电话号码的字母组合

作者:互联网

题目描述

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例:

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number

思路解析

回溯法:

  1. 维护一个哈希表,用来查找数字对应的字母表;
  2. 维护一个字符串,初始化为空,每次取一位数字,并将该数字的其中一个可能的字母插入到该字符串中,直至取完所有数字,即可得到一个解,将该解存入最终输出的容器中;
  3. 回溯:回退一位数字,更新其可能的字母,回退至第一位,即遍历所有情况。

在C++中采用unordered_map维护一个哈希表,unordered_mapmap的区别在于,unordered_map基于哈希表,其查找的时间复杂度为\(O(1)\),map基于红黑树,具有有序性,对于需要大量修改map中的内容时,map的时间复杂度为\(O(\log n)\)。
本例题中只需要查找,用unordered_map

代码实现

class Solution {
private:
    unordered_map<char, string> phoneMap{
        {'2', "abc"},
        {'3', "def"},
        {'4', "ghi"},
        {'5', "jkl"},
        {'6', "mno"},
        {'7', "pqrs"},
        {'8', "tuv"},
        {'9', "wxyz"}
    };

public:
    vector<string> letterCombinations(string digits) {
        vector<string> combinations;
        if(digits.empty()) return combinations;
        string combination;
        backtrack(combinations, digits, 0, combination);
        return combinations;
    }
    
    void backtrack(vector<string> &combinations, string digits, int index, string &combination) {
        if(index == digits.length()) {
            combinations.push_back(combination);
            return;
        }
        char digit = digits[index];
        string letters = phoneMap.at(digit);
        for(auto letter : letters) {
            combination.push_back(letter);
            backtrack(combinations, digits, index + 1, combination);
            combination.pop_back();
        }
    }
};

标签:digits,map,17,combination,unordered,combinations,字母组合,LeetCode,string
来源: https://www.cnblogs.com/xqmeng/p/13788637.html