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"].
1刷
方法1:DFS + Backtracking:
Time Complexity - O(3n), Space Complexity - O(n)。
方法2: BFS
方法1:
public class Solution {
public List<String> letterCombinations(String digits) {
String [] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
StringBuilder sb = new StringBuilder();
List<String> res = new ArrayList<>();
if(digits == null || digits.length() == 0) return res;
getLetterCombinations(res, sb, map, digits, 0);
return res;
}
private void getLetterCombinations(List<String> res, StringBuilder sb, String[] map, String digits, int pos) {
if(pos == digits.length()){
res.add(sb.toString());
return;
}
int index = digits.charAt(pos) - '0';
String letters = map[index];
for(int i=0; i<letters.length(); i++){
sb.append(letters.charAt(i));
getLetterCombinations(res, sb, map, digits, pos+1);
sb.setLength(sb.length()-1);
}
}
}
二刷
DFS
public class Solution {
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if(digits == null || digits.length() == 0) return res;
String [] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
StringBuilder sb = new StringBuilder();
dfs(0, digits, map, res, sb);
return res;
}
public void dfs(int index, String digits, String [] map, List<String> res, StringBuilder sb){
if(sb.length() == digits.length()){
res.add(sb.toString());
return;
}
int num = digits.charAt(index) - '0';
String cur = map[num];
for(int i=0; i<cur.length(); i++){
sb.append(cur.charAt(i));
dfs(index+1, digits, map, res, sb);
sb.setLength(sb.length()-1);
}
}
}