A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Although the above answer is in lexicographical order, your answer could be in any order you want.
class Solution {
public String[] helper(char c) {
if (c == '2')
return new String[] { "a", "b", "c" };
else if (c == '3')
return new String[] { "d", "e", "f" };
else if (c == '4')
return new String[] { "g", "h", "i" };
else if (c == '5')
return new String[] { "j", "k", "l" };
else if (c == '6')
return new String[] { "m", "n", "o" };
else if (c == '7')
return new String[] { "p", "q", "r", "s" };
else if (c == '8')
return new String[] { "t", "u", "v" };
else if (c == '9')
return new String[] { "w", "x", "y", "z" };
else
return new String[0];
}
public List<String> letterCombinations(String digits) {
List<String> ans = new ArrayList<>();
if (digits.length() == 0)
return ans;
backTrack(digits, ans, new StringBuilder(), 0);
return ans;
}
public void backTrack(String digits, List<String> ans, StringBuilder str, int start) {
if (start == digits.length()) {
ans.add(str.toString());
return;
}
String[] chars = helper(digits.charAt(start));
for (int i = 0; i < chars.length; i++) {
str.append(chars[i]);
backTrack(digits, ans, str, start + 1);
str.deleteCharAt(str.length() - 1);
}
}
}