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的索引。
leetcode17的更多相关文章
- Leetcode13. 罗马数字转整数Leetcode14. 最长公共前缀Leetcode15. 三数之和Leetcode16. 最接近的三数之和Leetcode17. 电话号码的字母组合
> 简洁易懂讲清原理,讲不清你来打我~ 输入字符串,输出对应整数 .注意 1 不对应任何字母. 示例: 输入:"23" 输出:[&quo ...
- 算法练习--LeetCode--17. Letter Combinations of a Phone Number
Letter Combinations of a Phone NumberMedium Given a string containing digits from 2-9 inclusive, ret ...
- 【1】【leetcode-17】电话号码的字母组合
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合. 给出数字到字母的映射如下(与电话按键相同).注意 1 不对应任何字母. 示例: 输入:"23"输出:[" ...
- string+DFS leetcode-17.电话号码下的字母组合
题面 Given a string containing digits from 2-9 inclusive, return all possible letter combinations that ...
- Leetcode17.Letter Combinations of a Phone Number电话号码的字母组合
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合. 给出数字到字母的映射如下(与电话按键相同).注意 1 不对应任何字母. 示例: 输入:"23" 输出:[&quo ...
- Java实现LeetCode17. 电话号码的字母组合
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合. 给出数字到字母的映射如下(与电话按键相同).注意 1 不对应任何字母. 示例: 输入:"23" 输出:[&quo ...
随机推荐
- Linux的相关概念
1 Linux的相关概念 1.1 什么是操作系统? 操作系统(英语:operating system,缩写:OS)是管理计算机硬件与软件资源的计算机程序,同时也是计算机系统的内核与基石.操作系统需要处 ...
- 初始Java
- 【Java】字符串工具类
import android.annotation.SuppressLint; import java.io.UnsupportedEncodingException; import java.uti ...
- Python全栈之路----函数进阶----装饰器
Python之路,Day4 - Python基础4 (new版) 装饰器 user_status = False #用户登录后改为True def login(func): #传入想调用的函数名 de ...
- 基于Jmeter的 性能测试
目标:对南通大学计算机学院网站开展性能测试:(url:http://cs.ntu.edu.cn/) 首先下载jmeter的zip压缩包,解压后进入bin目录,由于我使用的系统是win10,所以要双击执 ...
- psql的安装与数据库创建(ubuntu)
来自阮一峰日志 http://www.ruanyifeng.com/blog/2013/12/getting_started_with_postgresql --------------------- ...
- 【Jmeter】api性能测试总结
1.前提概念 平时常用的性能测试:api性能测试+场景性能测试:今天就说一说api性能测试 2.如何进行性能测试? 需求:对某api进行性能测试,看看最大承受的并发数,分析下图表 分析: 错误思路:当 ...
- pandas Dataframe 取某行
In [1]: df = DataFrame(randn(5,2),index=range(0,10,2),columns=list('AB')) In [2]: df Out[2]: A B 0 1 ...
- https://blog.csdn.net/doegoo/article/details/50749817
因为使用DiscuzX3.2进行系统的整合后,因为只是想在原J2EE的系统上增加论坛功能,而且J2EE中已经有一套用户的注册认证的体系,所以不需要在Discuz的系统中去注册以及登录功能,而是通过在J ...
- PHP的 preg_match_all
语法:int preg_match_all ( string pattern, string subject, array &matches [, int flags] ) 这个函数的返回值是 ...