给定一个仅包含数字?
2-9
?的字符串,返回所有它能表示的字母组合。答案可以按?任意顺序?返回。给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
class Solution {
private List<String> ans = new ArrayList<>();
private final String[] DIGITS = new String[]{"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public List<String> letterCombinations(String digits) {
if(digits.length() == 0){
return new ArrayList<>();
}
dfs(0,digits, new StringBuilder());
return ans;
}
private void dfs(int index, String digits,StringBuilder sb){
if(index == digits.length()){
ans.add(sb.toString());
return;
}
for (char c : DIGITS[Integer.parseInt(String.valueOf(digits.charAt(index)))].toCharArray()){
dfs(index + 1, digits, new StringBuilder(sb).append(c));
}
}
}