17. Letter Combinations of a Phone Number
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.
深度优先遍历
public List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<>();
if (digits == null || digits.length() == 0)
return list;
char[] tmp = new char[digits.length()];
String[] map = new String[] { "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
dfsSearch(digits, 0, map, tmp, list);
return list;
}
private void dfsSearch(String digits, int idx, String[] map, char[] tmp, List<String> list) {
if (idx == digits.length()) {
list.add(new String(tmp));
return;
}
// digits的第idx个字符cs - '2',正好为map数组的下标,
// 获得对应的字符串,'2'和'abc'对应
char cs = digits.charAt(idx);
// 类似图的深度优先遍历,固定一个点,继续递归剩下的邻接点
for (int i = 0; i < map[cs - '2'].length(); i++) {
// 让每个字符做第一位,继续递归后面剩下的字符
// 同一个层次的字符下标一样,都是idx
tmp[idx] = map[cs - '2'].charAt(i);
// 递归idx+1后面的字符
dfsSearch(digits, idx + 1, map, tmp, list);
}
}
参考:http://blog.youkuaiyun.com/china_wanglong/article/details/38495355
附录:字符的全排列(参考)
public void PermutationHelper(char[] chars, int i, ArrayList<String> list) {
if (i == chars.length) {
list.add(String.valueOf(chars));
return;
}
// 用于结果去重,可以用list
Set<Character> charSet = new HashSet<Character>();
for (int j = i; j < chars.length; ++j) {
if (!charSet.contains(chars[j])) {
charSet.add(chars[j]);
swap(chars, i, j);// 交换
PermutationHelper(chars, i + 1, list);
swap(chars, i, j);// 复原
}
}
}
public void swap(char[] cs, int i, int j) {
char temp = cs[i];
cs[i] = cs[j];
cs[j] = temp;
}
}