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.

分析

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

实现

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);
        }
    }
};

思考

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容