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.
这是个比较简单的DFS题,一般的递归就可以解决了。
public class Solution {
public List<String> letterCombinations(String digits) {
String[] codes = {"", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> result = new ArrayList<String>();
StringBuilder builder = new StringBuilder();
recursive(codes, result, builder, 0, digits);
return result;
}
public void recursive(String[] codes, List<String> result, StringBuilder builder, int depth, String digits){
if(depth == digits.length()){
result.add(builder.toString());
return;
}
int index = digits.charAt(depth) - '0';
for(int i = 0; i < codes[index].length(); i++){
builder.append(codes[index].charAt(i));
recursive(codes, result, builder, depth + 1, digits);
builder.deleteCharAt(builder.length() - 1);
}
}
}