Letter Combinations of a Phone Number (M)
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.
[外链图片转存失败(img-UBfZgokA-1564977537695)(assets/200px-Telephone-keypad2.svg.png)]
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.
题意
给定一个只包含 2-9 数字的字符串,要求返回由这些数字代表的字母组成的所有排列。
思路
使用类似于深度搜索的方法,每次先加入当前数字对应的一个字符,再递归处理右侧的数字,全部处理完成后删除该字符。
代码实现
class Solution {
public List<String> letterCombinations(String digits) {
// 特殊情况,直接返回空的List
if (digits.isEmpty()) {
return new ArrayList<String>();
}
String[] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> ans = new ArrayList<>();
generate(digits, map, "", ans);
return ans;
}
private void generate(String digits, String[] map, String s, List<String> ans) {
// 递归边界,无剩余数字可用说明已经完成了一个排列
if (digits.isEmpty()) {
ans.add(s);
return;
}
int first = digits.charAt(0) - '0';
for (int i = 0; i < map[first].length(); i++) {
s += map[first].charAt(i); // 先加入当前字符
generate(digits.substring(1), map, s, ans); // 递归处理右侧数字
s = s.substring(0, s.length() - 1); // 删除加入的字符
}
}
}