Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. class Solution {
public List<String> letterCombinations(String digits) {
String[] arr = new String[]{"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> res = new ArrayList<>();
if (digits == null || digits.length() < 1) return res;
dfs(res, 0, digits, arr, new StringBuilder());
return res;
}
private void dfs(List<String> res, int pos, String digits, String[] arr, StringBuilder path) {
if (pos == digits.length()) {
res.add(path.toString());
return;
}
int digit = digits.charAt(pos) - '0';
String chars = arr[digit];
for (int i = 0; i < chars.length(); ++i) {
path.append(chars.charAt(i));
dfs(res, pos + 1, digits, arr, path);
path.deleteCharAt(path.length() - 1);
}
}
}class Solution {
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
String[] arr = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
if (digits == null || digits.length() < 1) return res;
Deque<String> queue = new ArrayDeque<>();
queue.offerFirst("");
for (int i = 0; i < digits.length(); ++i) {
int size = queue.size();
String chars = arr[digits.charAt(i) - '0'];
for (int n = 0; n < size; ++n) {
String node = queue.pollLast();
for (char c : chars.toCharArray()) {
queue.offerFirst(node + c);
}
}
}
res.addAll(queue);
return res;
}
}