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