首页 > 编程语言 > 详细

17. Letter Combinations of a Phone Number C++回溯法

时间:2018-11-20 00:30:19      阅读:149      评论:0      收藏:0      [点我收藏+]

简单的回溯法!

class Solution {
public:
    void backTrack(string digits, vector<string> words, string ans, vector<string>& res, int k, int flag[])
    {
        if(k == digits.size())
        {
            res.push_back(ans);
        }
        else
        {
            for(int i=0; i<words[(int)(digits.at(k))-(int)0].size(); i++)
            {
                string t = ans;
                ans.push_back(words[(int)(digits.at(k))-(int)0].at(i));
                backTrack(digits,words,ans,res,k+1,flag);
                ans = t;//也可以直接ans.pop_back(),而不使用中间变量t
            }
        }
    }
    vector<string> letterCombinations(string digits) {
        string ans;
        int flag[4] = {0,};//0为未用过
        vector<string> words = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        vector<string> res;
        if(digits == "")
            return res;
        backTrack(digits,words,ans,res,0,flag);
        return res;
    }
};

技术分享图片

 

17. Letter Combinations of a Phone Number C++回溯法

原文:https://www.cnblogs.com/tornado549/p/9986708.html

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