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.


17. Letter Combinations of a Phone Number_第1张图片
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 letterCombinations(string digits) {
        vector ans;
        dfs(digits, 0, ans);
        return ans;
    }
private:
    vector character={"","","abc","def",
                              "ghi","jkl","mno",
                              "pqrs","tuv","wxyz"};
    void dfs(string& digits, size_t cur, vector& 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 Phone Number)