• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
THE WAY I AM
博客园    首页    新随笔    联系   管理    订阅  订阅
17. Letter Combinations of a Phone Number C++回溯法

简单的回溯法!

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

 

posted on 2018-11-19 23:58  549  阅读(110)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3