回溯法,深度优先遍历(DFS)

public class Solution
    {
        int[] x;
        int N;
        string DIGITS;
        Dictionary<char, List<string>> dic = new Dictionary<char, List<string>>();
        List<string> LIST = new List<string>();
        private void BackTrack(int t)
        {
            if (t >= N)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < N; i++)
                {
                    var dkey = DIGITS[i];
                    var temp = dic[dkey][x[i]];
                    sb.Append(temp);
                }
                LIST.Add(sb.ToString());
                return;
            }
            for (int i = 0; i < dic[DIGITS[t]].Count; i++)
            {
                x[t] = i;
                BackTrack(t + 1);
            }
        }
        private void Init()
        {
            dic.Add('2', new List<string> { "a", "b", "c" });
            dic.Add('3', new List<string> { "d", "e", "f" });
            dic.Add('4', new List<string> { "g", "h", "i" });
            dic.Add('5', new List<string> { "j", "k", "l" });
            dic.Add('6', new List<string> { "m", "n", "o" });
            dic.Add('7', new List<string> { "p", "q", "r", "s" });
            dic.Add('8', new List<string> { "t", "u", "v" });
            dic.Add('9', new List<string> { "w", "x", "y", "z" });
        }
        public IList<string> LetterCombinations(string digits)
        {
            var n = digits.Length;
            if (n > 0)
            {
                Init();
                N = n;
                x = new int[n];
                DIGITS = digits;
                BackTrack(0);
            }
            return LIST;
        }
    }

提供一种更直接的思路:

 1 public class Solution {
 2     public IList<string> LetterCombinations(string digits) {
 3         var combinations = new List<string>();
 4         
 5         if(string.IsNullOrEmpty(digits))
 6             return combinations;
 7         
 8         combinations.Add("");
 9         foreach(char digit in digits) {
10             var next = new List<string>();
11             
12             foreach(char letter in GetLetters(digit)) {
13                 foreach(string combo in combinations) {
14                     next.Add(combo + letter);
15                 }
16             }
17             combinations = next;
18         }
19         return combinations;
20     }
21     
22     public char[] GetLetters(char digit) {
23         switch (digit) {
24             case '2':
25                 return new char[] { 'a', 'b', 'c' };
26             case '3':
27                 return new char[] { 'd', 'e', 'f' };
28             case '4':
29                 return new char[] { 'g', 'h', 'i' };
30             case '5':
31                 return new char[] { 'j', 'k', 'l' };
32             case '6':
33                 return new char[] { 'm', 'n', 'o' };
34             case '7':
35                 return new char[] { 'p', 'q', 'r', 's' };
36             case '8':
37                 return new char[] { 't', 'u', 'v' };
38             case '9':
39                 return new char[] { 'w', 'x', 'y', 'z' };
40             default:
41                 return new char[0];
42         }
43     }
44 }

 

补充一个python的实现:

 1 class Solution:
 2     def backTrack(self,digits,dic,temp,res,i):
 3         if i == len(digits):
 4             res.append(''.join(temp[:]))
 5             return
 6         
 7         key = digits[i]
 8         li = dic[key]
 9         for j in range(len(li)):
10             temp.append(li[j])
11             self.backTrack(digits,dic,temp,res,i+1)
12             temp.pop(-1)
13         
14         
15     def letterCombinations(self, digits: 'str') -> 'List[str]':
16         n = len(digits)
17         if n == 0:
18             return []
19         res = []
20         dic = {'2':['a','b','c'],'3':['d','e','f'],'4':['g','h','i'],
21               '5':['j','k','l'],'6':['m','n','o'],'7':['p','q','r','s'],'8':['t','u','v'],'9':['w','x','y','z']}
22         self.backTrack(digits,dic,[],res,0)
23             
24         return res

思路:回溯法。

回溯函数的参数含义:

digits:原字符串,dic:按键字典,temp:字母组合的临时存储,res:最终结果的列表,i:digits的索引。

 

posted on 2018-10-05 17:48  Sempron2800+  阅读(242)  评论(0编辑  收藏  举报