17. Letter Combinations of a Phone Number
题目描述
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"].
解题方法
a: def
b: def
c: def
/*Recursive way : 先找到數字字符對應的字串以做相對應的排列組合*/
/*
private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
public List<String> letterCombinations(String digits) {
List<String> ret = new ArrayList<String>();
if(digits == null || digits.length() == 0){
return ret;
}
combination("", digits, 0, ret);
return ret;
}
private void combination(String prefix, String digits, int offset, List<String> ret) {
if (offset == digits.length()) {
ret.add(prefix);
return;
}
String letters = KEYS[(digits.charAt(offset) - '0')];
for (int i = 0; i < letters.length(); i++) {
combination(prefix + letters.charAt(i), digits, offset + 1, ret);
}
}
String[] key = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits){
LinkedList<String> lists = new LinkedList<>(); //* interface doesn't have peek() method
if(digits == null || digits.length() == 0){
return lists;
}
lists.add("");
for(int i = 0; i < digits.length(); i++){
char c = digits.charAt(i);
String mapping = key[c - '0'];
while( lists.peek().length() == i){
String prefix = lists.remove();
for(int j = 0; j < mapping.length(); j++){
lists.add(prefix + mapping.charAt(j));
}
}
}
return lists;
}