17. Letter Combinations of a Phone Number

欢迎fork and star:Nowcoder-Repository-github

17. 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.


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. 

《17. Letter Combinations of a Phone Number》

解析

  • 可以迭代,即依次读取字符串中的每位数字,然后把数字对应的字母依次加到当前的所有结果中,然后进入下一次迭代。也可以用递归来解,思路也类似,就是对于当前已有的字符串,递归剩下的数字串,然后得到结果后加上去。假设输入字符串总共有n个数字,平均每个数字可以代表m个字符,那么时间复杂度是O(m^n),确切点是输入字符串中每个数字对应字母数量的乘积,即结果的数量,空间复杂度也是一样。时间复杂度:O(m^n);空间复杂度:O(m^n)
// 17. Letter Combinations of a Phone Number
class Solution_17 {
public:

    // map<int, string> num2alp = { { 2, "abc" }, { 3, "def" }, { 4, "ghi" }, { 5, "jkl" }, { 6, "mno" }, { 7, "pqrs" }, { 8, "tuv" }, { 9, "wxyz" } };
    /*static const*/ vector<string> v = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
    void help(string digits,vector<string> &vec,string &temp,int index,int n)
    {
        if (index==n)
        {
            vec.push_back(temp);
            return;
        }
        string str = v[digits[index]-'0'];
        
        for (int i = 0; i < str.size();i++)
        {
            temp.push_back(str[i]);
            help(digits, vec,temp, index + 1,n);
            temp.pop_back();
        }
        return;
    }

    // 回溯递归实现
    vector<string> letterCombinations(string digits) { //23
        vector<string> vec;
        string temp;
        if (digits.size()==0)
        {
            vec.push_back(""); //初始化一个空
            return vec;
        }

        help(digits,vec,temp,0,digits.size());

        return vec;
    }

      // 迭代实现
    vector<string> letterCombinations_ref(string digits) {
        vector<string> result;
        if (digits.empty()) return vector<string>();
        static const vector<string> v = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
        result.push_back("");   // add a seed for the initial case
        for (int i = 0; i < digits.size(); ++i) {
            int num = digits[i] - '0';
            if (num < 0 || num > 9) break;
            const string& candidate = v[num];
            if (candidate.empty()) continue;
            vector<string> tmp;
            for (int j = 0; j < candidate.size(); ++j) {
                for (int k = 0; k < result.size(); ++k) {
                    tmp.push_back(result[k] + candidate[j]);
                }
            }
            result.swap(tmp); //
        }
        return result;
    }

};

题目来源

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8323822.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞