首页 > 代码库 > leetcode第18题--Letter Combinations of a Phone Number

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

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.

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