public class Solution {
public IList<string> LetterCombinations(string digits)
{
if(string.IsNullOrWhiteSpace(digits) || digits.Contains(‘1‘))
{
return new List<string>();
}
BuildMap();
var all = new List<char[]>();
for(var i = 0;i < digits.Length; i++){
all.Add(dict[digits[i]]);
}
var r = Find(all, 0);
return r;
}
private Dictionary<char, char[]> dict = new Dictionary<char, char[]>();
private IList<string> Find(IList<char[]> all, int row)
{
if(row == all.Count - 1){
var arr = new List<string>();
for(var i = 0;i < all[all.Count -1].Length; i++){
arr.Add(all[all.Count - 1][i].ToString());
}
return arr;
}
else{
var children = Find(all, row + 1);
var arr = new List<string>();
for(var i = 0;i < all[row].Length; i++){
var self = all[row][i];
for(var j = 0;j < children.Count; j++){
arr.Add(self + children[j]);
}
}
return arr;
}
}
private void BuildMap(){
dict.Add(‘2‘, new char[3]{‘a‘,‘b‘,‘c‘});
dict.Add(‘3‘, new char[3]{‘d‘,‘e‘,‘f‘});
dict.Add(‘4‘, new char[3]{‘g‘,‘h‘,‘i‘});
dict.Add(‘5‘, new char[3]{‘j‘,‘k‘,‘l‘});
dict.Add(‘6‘, new char[3]{‘m‘,‘n‘,‘o‘});
dict.Add(‘7‘, new char[4]{‘p‘,‘q‘,‘r‘,‘s‘});
dict.Add(‘8‘, new char[3]{‘t‘,‘u‘,‘v‘});
dict.Add(‘9‘, new char[4]{‘w‘,‘x‘,‘y‘,‘z‘});
}
}版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode -- Letter Combinations of a Phone Number
原文:http://blog.csdn.net/lan_liang/article/details/49108367