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.


    【分析】

     如果我們使用for循環來遍歷的話,也是可以求解的。但是,這道題目在參考了人家的解法之後,覺得使用基於回溯法的遞歸方式更加巧妙。

    注意:遞歸思路在編程的時候,一定要先寫跳出遞歸的條件if語句,然後再寫其餘的部分。而且,回溯法的思想是遍歷完一次之後,退一步,繼續遍歷,這個繼續遍歷的過程有時調用一次函數的過程,所以是遞歸方式。


    【代碼】

    注意:vector的初始化;還有string類型作爲一個容器,也是有push_back和pop_back函數的;回溯法的核心代碼local.pop_back()。

    運行時間:2ms

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        if(digits.size() == 0)
            return res;
            
        vector<string> phone(2, "");
        phone.push_back("abc");
        phone.push_back("def");
        phone.push_back("ghi");
        phone.push_back("jkl");
        phone.push_back("mno");
        phone.push_back("pqrs");
        phone.push_back("tuv");
        phone.push_back("wxyz");
        
        string local;
        backTracking(res, phone, digits, 0, local);
        
        return res;
    }
    
    void backTracking(vector<string>& res, vector<string>& phone, string& digits, int index, string& local)
    {
        if(index == digits.length())  // 作爲每次遍歷結束的出口
        {
            res.push_back(local);
            return;
        }
            
        for(int i = 0; i < phone[digits[index] - '0'].length(); i++)  // 遍歷每個按鍵包含的串長
        {
            local += phone[digits[index] - '0'][i];  // 連接當前字符
            backTracking(res, phone, digits, index + 1, local);  // 遍歷當前字符後面的情況
            local.pop_back();  // 回溯法的關鍵:遍歷好一次之後,退一步,繼續遍歷
        }
        // 全是引用類型,無返回值,簡潔
    }
};


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