回溯法 17. Letter Combinations of a Phone Number

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);
            }
        }
    }
};

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

 

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