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

17. Letter Combinations of a Pho

作者: Al73r | 来源:发表于2017-09-21 16:10 被阅读0次

    题目

    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.

    分析

    由于不知道输入的位数,所以需要用深度优点搜索。一开始想用栈来实现,但是搞了半天脑子都糊掉了,最后还是乖乖用递归,顺利完成。

    实现

    class Solution {
    public:
        vector<string> letterCombinations(string digits) {
            vector<string> ans;
            dfs(digits, 0, ans);
            return ans;
        }
    private:
        vector<string> character={"","","abc","def",
                                  "ghi","jkl","mno",
                                  "pqrs","tuv","wxyz"};
        void dfs(string& digits, size_t cur, vector<string>& ans, string tmp=""){
            if(cur>=digits.size()){
                if(tmp.size()>0) ans.push_back(tmp);
                return;
            }
            for(auto it: character[digits[cur]-'0']){
                dfs(digits, cur+1, ans, tmp+it);
            }
        }
    };
    

    思考

    递归的时候注意尽量不要传递复杂的数据结构。使用引用加上索引会比较快。

    相关文章

      网友评论

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

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