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

时间:2023-03-09 17:50:36
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.

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

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 = ; i < ss[s[len] -''].size(); ++i) // 进行深度优先搜索,len相当于depth
{
dfs(len + , s, t + ss[s[len] - ''][i], ans);
}
}
vector<string> letterCombinations(string digits)
{
vector<string> ans;
ans.clear();
if (digits.size() == )
{
ans.push_back("");
return ans;
}
dfs(, digits, "", ans);// 从第零层temp str 为空开始往深处搜索
return ans;
}