# Letter Combinations of a Phone Number

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.

Tips:

DFS：就是普通的dfs。。。

Code：

FIFO queue：

``````public class Solution {
public List<String> letterCombinations(String digits) {
List<String> ans = new ArrayList<String>();
if (digits.length() == 0) {
return ans;
}
String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
for (int i = 0; i < digits.length(); i++) {
int cur = Character.getNumericValue(digits.charAt(i));
while (ans.get(0).length() == i) {
String prev = ans.remove(0);
for (char c : mapping[cur].toCharArray()) {
}
}
}
return ans;
}
}
``````

DFS：

stringBuilder版

``````public class Solution {
String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<String>();
if (digits == null || digits.length() == 0) {
return result;
}
helper(digits, new StringBuilder(), result, 0);
return result;
}

private void helper(String digits, StringBuilder prev, List<String> result, int depth) {
if (depth >= digits.length()) {
return;
}
String letters = mapping[Character.getNumericValue(digits.charAt(depth))];
for (char c : letters.toCharArray()) {
prev.append(c);
helper(digits, prev, result, depth + 1);
prev.deleteCharAt(prev.length() - 1);
}
}
}
``````

String版

``````   public class Solution {
private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

public List<String> letterCombinations(String digits) {
combination("", digits, 0, ret);
return ret;
}

private void combination(String prefix, String digits, int offset, List<String> ret) {
if (offset >= digits.length()) {