17. Letter Combinations of a Phone Number
2016-04-20 23:08
281 查看
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.
思路:就是设置一个字典,然后回溯的组合就行
代码如下(已通过leetcode)
public class Solution {
public List<String> letterCombinations(String digits) {
String[] dicts={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
List<String> list=new ArrayList<String>();
if(digits==null||digits.length()==0) return list;
String temp="";
backtrace(list,digits,0,dicts,temp);
return list;
}
private void backtrace(List<String> list, String digits, int start, String[] dicts, String temp) {
// TODO Auto-generated method stub
if(start==digits.length()) {
list.add(temp);
return;
}
for(int i=start;i<digits.length();i++) {
String str=dicts[digits.charAt(i)-'0'];
for(int j=0;j<str.length();j++) {
temp=temp+str.charAt(j);
backtrace(list, digits, start+1, dicts, temp);
temp=temp.substring(0,temp.length()-1);
}
break;
}
}
}
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"].
思路:就是设置一个字典,然后回溯的组合就行
代码如下(已通过leetcode)
public class Solution {
public List<String> letterCombinations(String digits) {
String[] dicts={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
List<String> list=new ArrayList<String>();
if(digits==null||digits.length()==0) return list;
String temp="";
backtrace(list,digits,0,dicts,temp);
return list;
}
private void backtrace(List<String> list, String digits, int start, String[] dicts, String temp) {
// TODO Auto-generated method stub
if(start==digits.length()) {
list.add(temp);
return;
}
for(int i=start;i<digits.length();i++) {
String str=dicts[digits.charAt(i)-'0'];
for(int j=0;j<str.length();j++) {
temp=temp+str.charAt(j);
backtrace(list, digits, start+1, dicts, temp);
temp=temp.substring(0,temp.length()-1);
}
break;
}
}
}
相关文章推荐
- CSS实现多重边框和内凹圆角
- 国际工程承包项目风险识别与分析
- HDU - 2571 命运
- HDU 1018 Big Number
- 【BZOJ1095】[ZJOI2007]Hide 捉迷藏【动态树分治】
- 搭建SpringMVC+MyBatis开发框架五
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- Linux的帧缓冲(Frame Buffer)之三:LCD上显示摄像头
- Android Studio开发入门-引用jar及so文件
- 班级派团队项目小计(三)
- Linux内核分析期中总结
- 冲刺第二天
- CentOS常用repositories
- HDU - 1203 I NEED A OFFER!
- Ubuntu12.04新增屏幕分辨率
- 使用myeclipse10的WTP servers配置自己的tomcat
- listview中Button、ImageButton、CheckBox点击冲突
- 使用SPA(sql performance Analyzer)
- Leetcode 刷题: Best time to buy stock 2
- 【CodeChef-CSEQ】Count Sequences【Lucas定理】