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.
Simple backtracking.
public List<String> letterCombinations(String digits) {
List<String> results = new ArrayList<String>();
if (digits==null||digits.isEmpty()) {
return results;
}
String[] letters = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
combination(letters, results, new StringBuilder(), 0, digits);
return results;
}
public void combination(String[] letters, List<String> results, StringBuilder sb, int level, String digits) {
if (level==digits.length()) {
results.add(sb.toString());
return;
}
int currentDigit = digits.charAt(level)-'0';
for (int i=0; i<letters[currentDigit].length(); i++) {
sb.append(letters[currentDigit].charAt(i));
combination(letters, results, sb, level+1, digits);
sb.deleteCharAt(sb.length()-1);
}
}