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"].思路:排列组合的分期摊还(amortized)方法
1 从数字string一个数字开始扫描,求出当前数字对应的字母; 如2对应"abc"
2 把每个映射的字母,依附到结果集res的每个组合中,产生新的结果集,并返回;
3 扫描至数字结尾时,结果集就是所求的所有组合;
//amortized方法, 分期摊还法
public IList<string> LetterCombinations(string digits) {
IList<string> res=new List<string>();
if(digits==null||digits.Length==0)
return res;
//初始化,先加入空"
res.Add("");
//数字对应的字母0-9,其中0-1不对应任何字母
string[] mapArr=new string[]{"","","abc","def","ghi","jkl","mno","qprs","tuv","wxyz"};
char[] charArr=digits.ToCharArray();
for(int i=0; i<charArr.Count(); i++)
{
//获取该char对应的string
string curStr = mapArr[charArr[i]-'0'];
char[] curStrArr=curStr.ToCharArray();
IList<string> tmp=new List<string>();
for(int j=0;j < curStrArr.Count();j++)
//把每个对应的字母加入到每个结果集合
for(int k=0;k<res.Count();k++)
{
string TmpRes=(res[k] + curStrArr[j]).ToString();
tmp.Add(TmpRes);
}
//保存最新结果集
res=tmp;
}
return res;
}