leetcode17

时间:2023-03-09 06:31:04
leetcode17

回溯法,深度优先遍历(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 = ; i < N; i++)
{
var dkey = DIGITS[i];
var temp = dic[dkey][x[i]];
sb.Append(temp);
}
LIST.Add(sb.ToString());
return;
}
for (int i = ; i < dic[DIGITS[t]].Count; i++)
{
x[t] = i;
BackTrack(t + );
}
}
private void Init()
{
dic.Add('', new List<string> { "a", "b", "c" });
dic.Add('', new List<string> { "d", "e", "f" });
dic.Add('', new List<string> { "g", "h", "i" });
dic.Add('', new List<string> { "j", "k", "l" });
dic.Add('', new List<string> { "m", "n", "o" });
dic.Add('', new List<string> { "p", "q", "r", "s" });
dic.Add('', new List<string> { "t", "u", "v" });
dic.Add('', new List<string> { "w", "x", "y", "z" });
}
public IList<string> LetterCombinations(string digits)
{
var n = digits.Length;
if (n > )
{
Init();
N = n;
x = new int[n];
DIGITS = digits;
BackTrack();
}
return LIST;
}
}

提供一种更直接的思路:

 public class Solution {
public IList<string> LetterCombinations(string digits) {
var combinations = new List<string>(); if(string.IsNullOrEmpty(digits))
return combinations; combinations.Add("");
foreach(char digit in digits) {
var next = new List<string>(); foreach(char letter in GetLetters(digit)) {
foreach(string combo in combinations) {
next.Add(combo + letter);
}
}
combinations = next;
}
return combinations;
} public char[] GetLetters(char digit) {
switch (digit) {
case '':
return new char[] { 'a', 'b', 'c' };
case '':
return new char[] { 'd', 'e', 'f' };
case '':
return new char[] { 'g', 'h', 'i' };
case '':
return new char[] { 'j', 'k', 'l' };
case '':
return new char[] { 'm', 'n', 'o' };
case '':
return new char[] { 'p', 'q', 'r', 's' };
case '':
return new char[] { 't', 'u', 'v' };
case '':
return new char[] { 'w', 'x', 'y', 'z' };
default:
return new char[];
}
}
}

补充一个python的实现:

 class Solution:
def backTrack(self,digits,dic,temp,res,i):
if i == len(digits):
res.append(''.join(temp[:]))
return key = digits[i]
li = dic[key]
for j in range(len(li)):
temp.append(li[j])
self.backTrack(digits,dic,temp,res,i+)
temp.pop(-) def letterCombinations(self, digits: 'str') -> 'List[str]':
n = len(digits)
if n == :
return []
res = []
dic = {'':['a','b','c'],'':['d','e','f'],'':['g','h','i'],
'':['j','k','l'],'':['m','n','o'],'':['p','q','r','s'],'':['t','u','v'],'':['w','x','y','z']}
self.backTrack(digits,dic,[],res,) return res

思路:回溯法。

回溯函数的参数含义:

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