Given a digit string, return all possible letter combinations that the number could represent.
ex:
Input:Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
回溯算法,暴力搜索= =
ugly C# Code
public class Solution
{
Dictionary<char, List<char>> k = new Dictionary<char, List<char>>
{
{ '2', new List<char>{ 'a','b','c'} },
{ '3', new List<char>{ 'd','e','f'} },
{ '4', new List<char>{ 'g','h','i'} },
{ '5', new List<char>{ 'j','k','l'} },
{ '6', new List<char>{ 'm','n','o'} },
{ '7', new List<char>{ 'p','q','r','s'} },
{ '8', new List<char>{ 't','u','v'} },
{ '9', new List<char>{ 'w','x','y','z'} }
};
IList<string> anss = new List<string>();
public IList<string> LetterCombinations(string digits)
{
if (digits == "") return new List<string> { };
string ans = "";
calc(digits, 0, digits.Length, ans);
return anss;
}
private string calc(string d, int p, int max, string ans)
{
if (p == max)
{
anss.Add(ans);
return ans;
}
foreach (char c in k[d[p]])
{
calc(d, p + 1, max, ans + c);
}
return ans;
}
}
本文介绍了一种使用回溯算法解决数字字符串转字母组合的方法。通过建立数字与字母的映射关系,实现了从输入的数字字符串到所有可能的字母组合的转换。示例中详细展示了如何针对特定输入生成所有可能的输出。
518

被折叠的 条评论
为什么被折叠?



