Letter Combinations of a Phone Number
Last updated
Last updated
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].class Solution {
private final String[] mappings = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if (digits == null || digits.length() == 0) return res;
helper(res, digits, "", 0);
return res;
}
public void helper(List<String> res, String digits, String s, int index){
if (index == digits.length()) {
res.add(s);
return;
}
String letters = mappings[digits.charAt(index) - '0'];
for (int i = 0; i < letters.length(); i++) {
helper(res, digits, s + letters.charAt(i), index + 1);
}
}
}class Solution {
private final String[] mappings = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if (digits == null || digits.length() == 0) return res;
Queue<String> queue = new LinkedList<>();
queue.offer("");
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String word = queue.poll();
if (word.length() < digits.length()) {
int digit = digits.charAt(word.length()) - '0';
for (char c : mappings[digit].toCharArray()) {
queue.offer(word + c);
}
} else {
res.add(word);
}
}
}
return res;
}
}