LeetCode-17.Letter Combinations of a Phone Number

来源:互联网 发布:沈阳数据恢复公司 编辑:程序博客网 时间:2024/06/14 10:44

https://leetcode.com/problems/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"].

这是一道常规的递归题

public class Solution {    public IList<string> LetterCombinations(string digits)     {        IList<string> res = new List<string>();        if (digits.Length == 0)            return res;        Func(res,"", digits);        return res;    }        private void Func(IList<string> res,string s,string digits)    {        if (digits=="")        {            res.Add(s);            return;        }        int n = 3;        char c=digits[0];        if (c == '7' || c == '9')            n = 4;        for (int i = 0; i < n; i++)        {            s += getChar(c,i);            Func(res, s, digits.Substring(1));            s = s.Remove(s.Length - 1);        }    }            private string getChar(char c,int i)    {        if (c == '2')            return ((char)(97 + i)).ToString();        else if(c=='3')            return ((char)(100 + i)).ToString();        else if (c == '4')            return ((char)(103 + i)).ToString();        else if (c == '5')            return ((char)(106 + i)).ToString();        else if (c == '6')            return ((char)(109 + i)).ToString();        else if (c == '7')            return ((char)(112 + i)).ToString();        else if (c == '8')            return ((char)(116 + i)).ToString();        else            return ((char)(119 + i)).ToString();    }}

优化一下getChar函数

private string getChar(char c,int i)    {        int index = c - '2';        if (index<6)            return ((char)(97 + 3 * index + i)).ToString();        else             return ((char)(98 + 3 * index + i)).ToString();    }

方法2

public IList<string> LetterCombinations(string digits)     {        int len = digits.Length;        IList<string> res = new List<string>();        if (len == 0)            return res;        res.Add("");        string[] map =new string[] {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};        for (int i = 0; i < len; i++)        {            IList<string> list = new List<string>();            string str = map[digits[i] - '2'];            for (int j = 0; j < str.Length; j++)            {                for (int k = 0; k < res.Count; k++)                {                    list.Add(res[k] + str[j]);                }            }            res = list;        }        return res;    }
参考 https://leetcode.com/discuss/11261/my-iterative-sollution-very-simple-under-15-lines


0 0
原创粉丝点击