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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
Have you met this question in a real interview?
思路: 设置一个map 数组来存储对应的 字母, 每次用dfs 来做
public class Solution {
public List<String> letterCombinations(String digits) {
String[] map = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> list = new ArrayList<String>();
rec(digits, 0, map, new StringBuilder(), list);
return list;
}
public void rec(String digits, int pos , String[] map, StringBuilder sb, List<String> list) {
if(pos == digits.length()) {
list.add(sb.toString());
return;
}
String s = map[digits.charAt(pos)-'2'];
for(int i=0; i<s.length(); i++) {
sb.append(s.charAt(i));
rec(digits,pos+1, map, sb, list);
sb.deleteCharAt(sb.length()-1);
}
}
}