//本题用dfs的思路解题;
class Solution { public ListletterCombinations(String digits) { //建立list 收集结果用 List resultList = new ArrayList<>();
//判断是否为空
if(digits == null || digits.length() == 0) return resultList;
//建立一个具有映射关系的string数组
String[] myMap = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
//建立一个list 放入 映射过来的string; List digitToString = new ArrayList<>();
for(char c : digits.toCharArray()) {
digitToString.add(myMap[c - '0']);
}
int start = 0;
StringBuilder result = new StringBuilder();
helper(start, digitToString, resultList, result);
return resultList;
}
private void helper(int start, ListdigitToString, List resultList, StringBuilder result) {
if(start == digitToString.size()) {
resultList.add(result.toString());
return;
}
for(int i = 0; i < digitToString.get(start).length(); i++) {
result.append(digitToString.get(start).charAt(i));
helper(start + 1, digitToString, resultList, result);
result.deleteCharAt(result.length() - 1);
}
}
}
网友评论