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"].

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

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

示例:

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

思路:先建立一个映射表dict。在遍历数字时,在dict中取出数字对应的字符str。建立一个临时字符数组t,将str的每个字符都连接到 res的每个元素的后面。

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        if(digits.empty()) return {};
        vector<string> res{""};
        string dict[]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        for(int i=0;i<digits.size();++i)
        {
            string str=dict[digits[i]-'0'];
            vector<string> t;
            for(int j=0;j<str.size();j++)
                for(string s:res) t.push_back(s+str[j]);
            res = t;
        }return res;
    }
};

参考:http://www.cnblogs.com/grandyang/p/4452220.html

猜你喜欢

转载自blog.csdn.net/qq_21997625/article/details/85112853
今日推荐