码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode第18题--Letter Combinations of a Phone Number

时间:2014-10-18 23:48:28      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   strong   

Problem:

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

bubuko.com,布布扣

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

想了半天不知道怎么做,对递归真心不熟悉。特意看了算法导论的两个优先搜索,即广度优先和深度优先 bfs 和 dfs,这题用到的是dfs方法。

void dfs(int len, string s, string t, vector<string> &ans)
{
    string ss[] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    if (len == s.size()) // 当t已经存够s长度个的时候就可以push到答案中并返回
    {
        ans.push_back(t);
        return;
    }
    for (int i = 0; i < ss[s[len] -0].size(); ++i) // 进行深度优先搜索,len相当于depth
    {
        dfs(len + 1, s, t + ss[s[len] - 0][i], ans);
    }
}
vector<string> letterCombinations(string digits)
{
    vector<string> ans;
    ans.clear();
    if (digits.size() == 0)
    {
        ans.push_back("");
        return ans;
    }
    dfs(0, digits, "", ans);// 从第零层temp str 为空开始往深处搜索
    return ans;
}

 

leetcode第18题--Letter Combinations of a Phone Number

标签:style   blog   http   color   io   os   ar   for   strong   

原文地址:http://www.cnblogs.com/higerzhang/p/4034041.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!