美文网首页
[Leetcode] 43. Letter Combinatio

[Leetcode] 43. Letter Combinatio

作者: 时光杂货店 | 来源:发表于2017-03-20 20:12 被阅读13次

题目

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.

boke_0.png

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.

频度: 3

解题之法

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        if (digits.empty()) return res;
        string dict[] = {"0", "1", "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); //level 记录当前生成的字符串的字符个数
        else {
            string str = dict[digits[level] - '0'];
            for (int i = 0; i < str.size(); ++i) {
                out.push_back(str[i]);
                letterCombinationsDFS(digits, dict, level + 1, out, res);
                out.pop_back();
            }
        }
    }
};

相关文章

网友评论

      本文标题:[Leetcode] 43. Letter Combinatio

      本文链接:https://www.haomeiwen.com/subject/bopinttx.html