17. Letter Combinations of a Phone Number

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.

public IList<string> LetterCombinations(string digits) {
        string[] dic = new string[]{"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        IList<string> result = new List<string>();
        if(digits.Length == 0) return result;
        result.Add("");
        for(int i =0; i< digits.Length;i++)
        {
            IList<string> temp = new List<string>();
            string digit = dic[digits[i]-'0'];
            for(int j = 0;j< digit.Length ;j++)
            {
                for(int m = 0; m< result.Count();m++)
                {
                    temp.Add(result[m] + digit[j]);
                }
            }
            result = temp;
        }
        return result;
    }

或者用recursive的方法。

public IList<string> LetterCombinations(string digits) {
        var res = new List<string>();
        var cur = new List<char>();
        if(digits =="") return res;
        var dic = new Dictionary<char,List<char>>();
        dic.Add('2',new List<char>{'a','b','c'});
        dic.Add('3',new List<char>{'d','e','f'});
        dic.Add('4',new List<char>{'g','h','i'});
        dic.Add('5',new List<char>{'j','k','l'});
        dic.Add('6',new List<char>{'m','n','o'});
        dic.Add('7',new List<char>{'p','q','r','s'});
        dic.Add('8',new List<char>{'t','u','v'});
        dic.Add('9',new List<char>{'w','x','y','z'});
        BackTracking(digits,0,res,cur,dic);
        return res;
        
    }
    private void BackTracking(string digits,int index, IList<string> res, List<char> cur, Dictionary<char,List<char>> dic)
    {
        if(index >= digits.Count())
        {
            res.Add(new string(cur.ToArray()));
        }
        else
        {
            foreach( char c in dic[digits[index]])
            {
                cur.Add(c);
                BackTracking(digits,index+1,res,cur,dic);
                cur.RemoveAt(cur.Count()-1);
            }
        }
    }
原文地址:https://www.cnblogs.com/renyualbert/p/5875906.html