首页 > 其他 > 详细

回溯法 17. Letter Combinations of a Phone Number

时间:2019-03-28 18:34:06      阅读:158      评论:0      收藏:0      [点我收藏+]
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

原文:https://www.cnblogs.com/buddho/p/10616745.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!