标签:
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"].
public class Solution {
public List<String> letterCombinations(String digits) {
List<String> result=new ArrayList<String>();
if(digits==null || digits.length()==0){
return result;
}
List<String> list=new ArrayList<String>();
for(int i=0; i<digits.length(); i++){
char c=digits.charAt(i);
if(c==‘2‘){
list.add("abc");
}
else if(c==‘3‘){
list.add("def");
}
else if(c==‘4‘){
list.add("ghi");
}
else if(c==‘5‘){
list.add("jkl");
}
else if(c==‘6‘){
list.add("mno");
}
else if(c==‘7‘){
list.add("pqrs");
}
else if(c==‘8‘){
list.add("tuv");
}
else if(c==‘9‘){
list.add("wxyz");
}
}
StringBuilder sb=new StringBuilder();
dfs(list, 0, sb, result);
return result;
}
public void dfs(List<String> inputs, int step,StringBuilder sb,List<String> res){
if(step==inputs.size()){
res.add(sb.toString());
return;
}
String str=inputs.get(step);
for(int i=0; i<str.length(); i++){
sb.append(str.charAt(i));
dfs(inputs, step+1, sb, res);
sb.deleteCharAt(sb.length()-1);
}
}
}
Leetcode-Letter Combinations of a Phone Number
标签:
原文地址:http://www.cnblogs.com/incrediblechangshuo/p/5697694.html