[Leetcode] 43. Letter Combinations of a Phone Number

题目

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.

[Leetcode] 43. Letter Combinations of a Phone Number_第1张图片
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 letterCombinations(string digits) {
        vector 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 &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 Combinations of a Phone Number)