目录

题目描述:

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

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

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

 leetcode 17. 电话号码的字母组合(Letter Combinations of a Phone Number) 随笔

示例:

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

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

解法:

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        if(digits.empty()){
            return res;
        }else{
            res.push_back("");
        }
        
        vector<string> strs = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        int sz = 1;
        for(char d : digits){
            int idx = int(d - '0');
            vector<string> tmp;
            for(int i = 0; i < sz; i++){
                for(char ch : strs[idx]){
                    tmp.push_back(res[i] + ch);
                }
            }
            sz *= strs[idx].size();
            res = tmp;
        }
        return res;
    }
};
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄