【medium】17. Letter Combinations of a Phone Number 數字組合

class Solution {
public:
    vector<string> ans; // answers
    
    // dfs實現
    void dfs (int x, int l, string str, string digits, char phone[][4]){
        if (x==l){
            ans.push_back(str);
            return;
        }
        int num = digits[x] - '0';
        for (int i=0;i<4;i++){
            if (phone[num][i]){
                dfs(x+1, l, str+phone[num][i], digits, phone);
            }
        }
    }
    
    vector<string> letterCombinations(string digits) {
        char phone[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'}};
        
        if (digits.length() == 0)
            return ans;
        
        // dfs算法!
        dfs(0, digits.length(), "", digits, phone);
            
        return ans;
        
    }
};

給一個不包含'0''1'的數字字符串,每一個數字表明一個字母,請返回其全部可能的字母組合。git

下圖的手機按鍵圖,就表示了每一個數字能夠表明的字母。算法

1 2
ABC
3
DEF
4
GHI
5
JKL
6
MNO
7
PQRS
8
TUV
9WXYZ
相關文章
相關標籤/搜索