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

回溯就是递归。把大问题分解成小问题?不知道是怎么描述这个思想。

 

posted on 2019-03-28 18:04  newbird2017  阅读(105)  评论(0编辑  收藏  举报