从第一个数字开始遍历其对应的字母,将其加入StringBuffer中,继续深度优先搜索,当访问到最后一个数字的时候,将StringBuffer存储到ans中,然后回溯到下一个对应字母。
java
class Solution {
public List<String> letterCombinations(String digits) {
List<String> ans = new ArrayList<>();
if (digits.length() == 0) return ans;
Map<Character, String> map = new HashMap<>() {
{
put('2', "abc");
put('3', "def");
put('4', "ghi");
put('5', "jkl");
put('6', "mno");
put('7', "pqrs");
put('8', "tuv");
put('9', "wxyz");
}
};
backtrack(ans, digits, map, 0, new StringBuffer());
return ans;
}
public void backtrack(List<String> ans, String digits, Map<Character, String> map, int index, StringBuffer sb) {
if (index == digits.length()) ans.add(sb.toString());
else {
char ch = digits.charAt(index);
String letters = map.get(ch);
for (int i = 0; i < letters.length(); ++i) {
sb.append(letters.charAt(i));
backtrack(ans, digits, map, index + 1, sb);
sb.deleteCharAt(index);
}
}
}
}
拓展:
StringBuffer中的删除对应字符的方法是deleteCharAt()