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"].
簡單的回溯實現
class Solution {
public:
    //回溯法
    void DFS(string digits, int n, int curIndex, string curStr, unordered_map<char, string> &cmap, vector<string> &ans)
    {
        if(curIndex > n)
            return;
        if(curIndex == n)
        {
            ans.push_back(curStr);
            return;
        }
        
        int tmpLen = cmap[digits[curIndex]].size();
        for(int i = 0; i< tmpLen; ++i)
        {
            curStr.push_back(cmap[digits[curIndex]][i]);
            DFS(digits, n, curIndex + 1, curStr, cmap, ans);
            curStr.pop_back();
        }
    }
    
    vector<string> letterCombinations(string digits) {
        int len = digits.size();
        vector<string> ans;
        if(len >= 1)
        {
            unordered_map<char, string> cmap;
            cmap['2'] = "abc";
            cmap['3'] = "def";
            cmap['4'] = "ghi";
            cmap['5'] = "jkl";
            cmap['6'] = "mno";
            cmap['7'] = "pqrs";
            cmap['8'] = "tuv";
            cmap['9'] = "wxyz";
            string curStr = "";
            DFS(digits, len, 0, curStr, cmap, ans);
        }
        
        return ans;
    }
};


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