Middle-题目72:17. Letter Combinations of a Phone Number
2016-05-31 16:51
417 查看
题目原文:
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”].
题目大意:
给出一个九键键盘,和数字序列,求出所有可能的对应字母组合。
题目分析:
还是一个暴力的回溯法,使用backtrack(List list, String digits, String currentLetter, int index)维护搜索过程,其中list是字母组合的列表,digits是数字序列,currentLetter是当前的搜索结果,index记录digits串中该搜索的位置。
源码:(language:java)
成绩:
1ms,beats 46.02%,众数1ms,53.98%
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”].
题目大意:
给出一个九键键盘,和数字序列,求出所有可能的对应字母组合。
题目分析:
还是一个暴力的回溯法,使用backtrack(List list, String digits, String currentLetter, int index)维护搜索过程,其中list是字母组合的列表,digits是数字序列,currentLetter是当前的搜索结果,index记录digits串中该搜索的位置。
源码:(language:java)
public class Solution { private String[][] letters = new String[][] { {" "}, {}, {"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"} }; public List<String> letterCombinations(String digits) { List<String> list = new ArrayList<String>(); if(digits.length() > 0) backtrack(list, digits, new String(), 0); return list; } private void backtrack(List<String> list, String digits, String currentLetter, int index) { if(index == digits.length()) { list.add(currentLetter); return; } else { int num = digits.charAt(index) -'0'; for(int i = 0; i < letters[num].length; i++) { currentLetter+=letters[num][i]; backtrack(list, digits, currentLetter, index+1); currentLetter = currentLetter.substring(0,currentLetter.length()-1); } } } }
成绩:
1ms,beats 46.02%,众数1ms,53.98%
相关文章推荐
- 计算机网络基础--网络端口分类
- 第14课:Spark Streaming源码解读之State管理之updateStateByKey和mapWithState解密
- hdu2476(区间dp+普通dp)
- 服务器监控之zabbix监控Tomcat篇
- 大话数据结构:线性表(3)
- 创建表空间
- requestWindowFeature使用详解
- hiho_1078_线段树区间修改
- 高效使用STL
- 操作系统设计与实现 第二章 进程(五)
- [Ruby On Rails] Action Controller - 控制HTTP 流程
- Android跨进程通信一 Messenger
- java 内部类
- spring(3)高级装配
- HTML5定稿了,为什么原生App世界将被颠覆
- 学习练习 java 输入输出流练习2
- ubuntu下nfs服务器的安装与配置
- eclipse java.lang.OutOfMemoryError: Java heap space
- NumberPicker中ArrayIndexOutOfBoundsException解决方案
- Java读写文件方法总结(推荐)