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.

分析

由于不知道輸入的位數(shù),所以需要用深度優(yōu)點搜索。一開始想用棧來實現(xiàn),但是搞了半天腦子都糊掉了,最后還是乖乖用遞歸,順利完成。

實現(xiàn)

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

思考

遞歸的時候注意盡量不要傳遞復(fù)雜的數(shù)據(jù)結(jié)構(gòu)。使用引用加上索引會比較快。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容