Chinaunix首页 | 论坛 | 博客
  • 博客访问: 266815
  • 博文数量: 170
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1709
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-06 18:01
文章分类

全部博文(170)

文章存档

2016年(11)

2015年(130)

2014年(29)

分类: Java

2015-04-01 16:50:16

//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"].


import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import experience.ListSet;


public class LetterCombinationsofaPhoneNumber {


public static void main(String[] args) {
// TODO 自动生成的方法存根
System.out.print(letterCombinations("23"));
}
public static List letterCombinations(String digits) {
if(digits==null||digits.length()==0)
return Collections.EMPTY_LIST;
List result=new ArrayList();
Map map=new HashMap();
Character[] two=new Character[]{
'a','b','c'
};
map.put('2', two);
two=new Character[]{
'd','e','f'
};
map.put('3', two);
two=new Character[]{
'g','h','i'
};
map.put('4', two);
two=new Character[]{
'j','k','l'
};
map.put('5', two);
two=new Character[]{
'm','n','o'
};
map.put('6', two);
two=new Character[]{
'p','q','r','s'
};
map.put('7', two);
two=new Character[]{
't','u','v'
};
map.put('8', two);
two=new Character[]{
'w','x','y','z'
};
map.put('9', two);
StringBuilder sb=new StringBuilder();
dfs(digits,result,map,sb,0);
return result;
 
}
private static void dfs(String digits, List result,
Map map,StringBuilder sb,int i) {
// TODO 自动生成的方法存根
if(i==digits.length()){
result.add(sb.toString());
return;
}

Character[] chars=map.get(digits.charAt(i));
for(int j=0;j sb.append(chars[j]);
dfs(digits, result, map, sb, i+1);
sb.replace(i, i+1, "");
}
}
}

阅读(406) | 评论(0) | 转发(0) |
0

上一篇:3Sum Closest

下一篇:4Sum

给主人留下些什么吧!~~