17. Letter Combinations of a Phone Number
2016-01-22 11:36
218 查看
Letter Combinations of a Phone Number
Input:Digit string “23”Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
使用回溯法:
public class Solution { List<String> list; //需要全局的 public List<String> letterCombinations(String digits) { list=new ArrayList<String>(); if(digits.length()==0) return list; backTrack(digits,"",0); //digits第一个数字 return list; } void backTrack(String digits,String letter,int index){ if(index>=digits.length()){ list.add(new StringBuilder(letter).toString()); return; } int num = digits.charAt(index) - '2'; //键盘数字、字母是从2开始的 int end; if(num==5||num==7) end=4; //数字7和9是四个字母 else end=3; for(int i=0;i<end;i++){ char c; if(num<5) c=(char)('a'+(num*3+i)); else if(num==5) c=(char)('p'+i); //7 else if(num==6) c=(char)('t'+i); //8 else c=(char)('w'+i); //9 String newLetter = new StringBuilder(letter).toString(); backTrack(digits,letter+c,index+1); } } }
相关文章推荐
- Java(.NET)经典排序算法之选择排序
- uva1471 - Defense Lines (最长上升子序列变形)
- poj 2996 Help Me with the Game
- Java IO流(概述)
- 道与JAVA(二)
- python IO编程
- JavaScript回调方法中使用外部变量出现的问题
- iOS数据库存储数组或字典等数据
- 页面回显获取值栈对象属性
- 使用SDWebImage 清除App 缓存
- 多线程synchronized用例解析
- KVC KVO
- iOS数据库存储数组或字典等数据
- 超类
- iOS 数组遍历删除元素的问题
- /dev/ipldevice 作用
- python学习笔记-Day12-- memcached / redis / rabbitMQ / sqlalchemy
- NSMutableAttributedString使用
- SharePrefrence,支持存取int,string,boolean,long,float,以及清空整个share存储的数据。
- 数据窗口进行动态修改