leetcode: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"].

題意&解題思路:

按照所給電話號碼的順序輸出所有可能的字母組合。先構造一個數字對應字母的字符數組a,

char a[10][4] = {
        {}, {}, {'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'}, 
        {'j', 'k', 'l'}, {'m','n', 'o'}, {'p', 'q', 'r', 's'},
        {'t', 'u', 'v'}, {'w', 'x', 'y', 'z'}
    };

嗯,大致長醬紫吧,然後按照上面給的字母進行dfs,搜到最後一個就輸出就好。需要注意的是,含有 0 和 1 字符的串在本題都是沒有組合,返回空的vector。其他沒啥值得注意的點。(不過輸入含有其他字符如'a23'這種,判題系統也跟着出錯,沒有對這些非法輸入進行判斷)。代碼如下:

class Solution {
public:
    char a[10][4] = {
        {}, {}, {'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'}, 
        {'j', 'k', 'l'}, {'m','n', 'o'}, {'p', 'q', 'r', 's'},
        {'t', 'u', 'v'}, {'w', 'x', 'y', 'z'}
    };
    void dfs(string str, vector<string>& ans, string s){
        int len = 3, x = str[0] - '0';
        if(x == 7 || x == 9)len++;
        if(str.length() == 1){
            for(int i = 0; i < len; i++)ans.push_back(s + a[x][i]);
            return;
        }
        for(int i = 0; i < len; i++){
            dfs(str.substr(1, str.length() - 1), ans, s + a[x][i]);
        }
    }
    vector<string> letterCombinations(string digits) {
        vector<string> ans;
        int len = digits.length();
        int ind = 0;
        while(ind < len){
            if(digits[ind] == '0' || digits[ind] == '1')return ans;
            ind++;
        }
        if(digits.length() == 0)return ans;
        string s = "";
        dfs(digits, ans, s);
        return ans;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章