c# LeetCode17 电话号码的字母组合(贪心算法)

回溯算法:

 

public class Solution {    
    List res = new List();    
    public IList LetterCombinations(string digits) 
    {         
        if (string.IsNullOrWhiteSpace(digits)) return res;
        Dictionary map = new Dictionary()
        {
            {'2', "abc"},
            {'3', "def"},
            {'4', "ghi"},
            {'5', "jkl"},
            {'6', "mno"},
            {'7', "pqrs"},
            {'8', "tuv"},
            {'9', "wxyz"}
        };
        _LetterCombinations(digits, String.Empty, map, 0);

        return res;
    }
    private void _LetterCombinations(string digits, string log, Dictionary map, int level)
    {
        //排列组合->回溯->回溯模板=》_,_,_
        if (log.Length == digits.Length) //terminator
        {
            res.Add(log);
            return;
        }

        string str = map[digits[level]]; //当前层选择列表
        for (int i = 0; i < str.Length; i++) //遍历列表
        {
            log = log + str[i]; //进行选择
            _LetterCombinations(digits, log, map, level + 1); //drill down
            log = log.Remove(log.Length - 1); //恢复当前状态
        }
        //reverse
    }
}

 

 

 

 

贪心算法(又称贪婪算法)是指,在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,他所做出的是在某种意义上的局部最优解。
贪心算法不是对所有问题都能得到整体最优解,关键是贪心策略的选择,选择的贪心策略必须具备无后效性,即某个状态以前的过程不会影响以后的状态,只与当前状态有关。

 

 

 

                             ε=(´ο`*)))

public static IList LetterCombinations(string digits)
		{
			IList curr = new List();
			if (digits.Length == 0) return curr;

			curr.Add("");
			foreach (char d in digits)
			{
				IList next = new List();
				foreach (char letter in GetLetters(d))
				{
					foreach (string s in curr)
					{
						next.Add(s + letter);
					}
				}
				curr = next;
			}
			return curr;
		}

		private static char[] GetLetters(char digit)
		{
			 switch (digit)
			{
				case '2':
					return new char[] { 'a', 'b', 'c' };
				case '3':
					return new char[] { 'd', 'e', 'f' };
				case '4':
					return new char[] { 'g', 'h', 'i' };
				case '5':
					return new char[] { 'j', 'k', 'l' };
				case '6':
					return new char[] { 'm', 'n', 'o' };
				case '7':
					return new char[] { 'p', 'q', 'r','s' };
				case '8':
					return new char[] { 't', 'u', 'v' };
				case '9':
					return new char[] { 'w', 'x', 'y','z' };  
				default:
					return new char[0];
			}
		}

 

		public static void Main(string[] args)
		{
			string  c = "234";
			IList res= LetterCombinations(c);
			Console.WriteLine(res);
			Console.ReadKey();
		}

 

你可能感兴趣的:(Leetcode,回溯算法)