Problem:
Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.
Explanation:
找出拨号键盘上两个数字对应英文的所有两两组合。
My Thinking:
My Solution:
Optimum Thinking:
使用map将数字和字母对应关系存入,使用递归对数字对应字母进行组合。
Optimum Solution:
class Solution {
private List<String> output=new ArrayList<String>();
private Map<String,String> numletter=new HashMap<>();
public List<String> letterCombinations(String digits) {
numletter.put("2","abc");
numletter.put("3","def");
numletter.put("4","ghi");
numletter.put("5","jkl");
numletter.put("6","mno");
numletter.put("7","pqrs");
numletter.put("8","tuv");
numletter.put("9","wxyz");
if(digits.length()!=0)
backtrack("",digits);
return output;
}
public void backtrack(String combination,String next_digits){
if(next_digits.length()==0){
output.add(combination);
}else{
String digit=next_digits.substring(0,1);
String letters=numletter.get(digit);
for (int i = 0; i < letters.length(); i++) {
String letter = numletter.get(digit).substring(i, i + 1);
backtrack(combination + letter, next_digits.substring(1));
}
}
}
}