Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.
Example:
Input: "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.
分析:
使用回溯,用temp记录路径。当遍历到叶子结点时,一个结果就生成了。
Java:
class Solution {
List<String> res = new ArrayList<>();
StringBuilder temp = new StringBuilder();
String[] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
void dfs(int index, String digits) {
if (index == digits.length()) {
res.add(temp.toString());
return;
}
int num = digits.charAt(index) - '0';
for (int i = 0; i < map[num].length(); i++) {
temp.append(map[num].charAt(i));
dfs(index + 1, digits);
temp.deleteCharAt(temp.length() - 1);
}
}
public List<String> letterCombinations(String digits) {
if ("".equals(digits)) {
return new ArrayList<>();
}
dfs(0, digits);
return res;
}
}