Letter Combinations of a Phone Number——解題報告 (回溯法的應用 ),lettercombinations

來源:互聯網
上載者:User

Letter Combinations of a Phone Number——解題報告 (回溯法的應用 ),lettercombinations


    【題目】

      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();  // 回溯法的關鍵:遍曆好一次之後,退一步,繼續遍曆        }        // 全是參考型別,無傳回值,簡潔    }};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.