1. 程式人生 > >回溯法 17. Letter Combinations of a Phone Number

回溯法 17. Letter Combinations of a Phone Number

cto amp col 最終 追加 num back 分解 n-1

class Solution {
public:
    map<char,string> dict;

    vector<string> letterCombinations(string digits) {        
dict[
2] = "abc"; dict[3] = "def"; dict[4] = "ghi"; dict[5] = "jkl"; dict[6] = "mno"; dict[7] = "pqrs
"; dict[8] = "tuv"; dict[9] = "wxyz"; vector<string> ans; helper(digits, digits.size(), ans); return ans; } // 先把前n-1個實現,然後在前面的結果中追加第n個數字對應的字母,就是最終的結果。 void helper(string &digits, int n, vector<string>& ans) {
if(n == 0) return;
     //第n個數
char num = digits[n-1]; if(n == 1) { for(auto c:dict[num])//對每個字母 ans.push_back(string(1,c)); return; } //先獲得前n-1個數字組成的字符串數組
        vector<string> a;
     helper(digits, n-1
, a); for(auto c: dict[num])// 把第n-1個數字,追加到每一個 { for(auto str: a) { str.push_back(c); ans.push_back(str); } } } };

回溯就是遞歸。把大問題分解成小問題?不知道是怎麽描述這個思想。

回溯法 17. Letter Combinations of a Phone Number