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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
public class Solution {
public List<String> letterCombinations(String digits) {
List<char[]> list = new ArrayList<char[]>();
list.add(new char[]{' '});
list.add(new char[]{});
list.add(new char[]{'a','b','c'});
list.add(new char[]{'d','e','f'});
list.add(new char[]{'g','h','i'});
list.add(new char[]{'j','k','l'});
list.add(new char[]{'m','n','o'});
list.add(new char[]{'p','q','r','s'});
list.add(new char[]{'t','u','v'});
list.add(new char[]{'w','x','y','z'});
List<String> ret = new ArrayList<String>();
ret.add("");
return build(ret, list, digits, 0);
}
private List<String> build(List<String> ret, List<char[]> list,
String digits, int i) {
if (0 == digits.length()) {
return new ArrayList<String>();
}
if (i == digits.length()) {
return ret;
}
int pos = digits.charAt(i)-'0';
char[] str = list.get(pos);
if (str.length == 0) {
return ret;
}
List<String> newRet = new ArrayList<String>();
for (String s : ret) {
for (char ch : str) {
newRet.add(s+ch);
}
}
return build(newRet, list, digits, i+1);
}
}