美文网首页
17. Letter Combinations of a Pho

17. Letter Combinations of a Pho

作者: weego | 来源:发表于2018-04-06 00:00 被阅读0次

Description

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.


phone.png
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Solution

  • 递归调用
vector<string> letterCombinations(string digits) {
    vector<string> letters = {"", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    vector<string> ret;
    if (digits.length() == 0) {
        return ret;
    }
    this->dfsLetterCombinations(ret, "", digits, letters, 0);
    return ret;
}
void dfsLetterCombinations(vector<string>& ret, string path, string digits, vector<string> letters, int depth) {
    if (path.size() == digits.size()) {
        ret.push_back(path);
        return;
    }
    string curLetters = letters[digits[depth] - '1'];
    for (int i = 0; i < curLetters.size(); ++i) {
        this->dfsLetterCombinations(ret, path + curLetters[i], digits, letters, depth + 1);
    }
}
  • 迭代法
    类似二叉树层次遍历,每经过一轮次,ret数组要在上一轮的基础上扩大3/4倍规模,借助curRet不断调整结果
vector<string> letterCombinations(string digits) {
    vector<string> letters = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    vector<string> ret;
    if (digits.size() == 0) {
        return ret;
    }
    ret.push_back("");
    for (int i = 0; i < digits.length(); ++i) {
        vector<string> curRet;
        string curLetters = letters[digits[i] - '0'];
        for (int j = 0; j < curLetters.length(); ++j) {
            for (int k = 0; k < ret.size(); ++k) {
                curRet.push_back(ret[k] + curLetters[j]);
            }
        }
        ret = curRet;
    }
    return ret;
}

相关文章

网友评论

      本文标题:17. Letter Combinations of a Pho

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