LeetCode #17 Letter Combinations of a Phone Number C# Solution

来源:互联网 发布:微信聊天记录数据库 编辑:程序博客网 时间:2024/06/09 05:30

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;        }    }

这里写图片描述

0 0
原创粉丝点击