zoukankan      html  css  js  c++  java
  • 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);
                }
            }
        }
  • 相关阅读:
    VC++MFC对话框程序中给对话添加背景图片
    C++中的引用
    64位Ubuntu 13.04 安装Bochs 2.3.5
    笔记
    ORG 07C00H的意思
    编译三思
    《黑客与画家》笔记
    linux 2.6up的设备和设备驱动模型
    linux嵌入式系统驱动程序的阻塞与异步
    【转】PWM占空比和分辨率
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5875906.html
Copyright © 2011-2022 走看看