17. 電話號碼的字母組合
難度中等1276收藏分享切換為英文接收動態(tài)反饋
給定一個僅包含數(shù)字 2-9
的字符串,返回所有它能表示的字母組合。答案可以按 任意順序 返回锅铅。
給出數(shù)字到字母的映射如下(與電話按鍵相同)械筛。注意 1 不對應(yīng)任何字母。
img
示例 1:
輸入:digits = "23"
輸出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:
輸入:digits = ""
輸出:[]
示例 3:
輸入:digits = "2"
輸出:["a","b","c"]
提示:
0 <= digits.length <= 4
-
digits[i]
是范圍['2', '9']
的一個數(shù)字启绰。
- 1Letter Combinations of a Phone Number
Medium
5917522Add to ListShare
Given a string containing digits from 2-9
inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
[站外圖片上傳中...(image-c41852-1619398504333)]
Example 1:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = ""
Output: []
Example 3:
Input: digits = "2"
Output: ["a","b","c"]
Constraints:
0 <= digits.length <= 4
-
digits[i]
is a digit in the range['2', '9']
.
方法:暴力遞歸号涯,深度優(yōu)先遍歷
image-20210426084946288
class Solution {
public static char[][] phone = {
{ 'a', 'b', 'c' }, // 2 0
{ 'd', 'e', 'f' }, // 3 1
{ 'g', 'h', 'i' }, // 4 2
{ 'j', 'k', 'l' }, // 5 3
{ 'm', 'n', 'o' }, // 6
{ 'p', 'q', 'r', 's' }, // 7
{ 't', 'u', 'v' }, // 8
{ 'w', 'x', 'y', 'z' }, // 9
};
// "23"
public static List<String> letterCombinations(String digits) {
List<String> ans = new ArrayList<>();
if (digits == null || digits.length() == 0) {
return ans;
}
char[] str = digits.toCharArray();
char[] path = new char[str.length];
process(str, 0, path, ans);
return ans;
}
// str = ['2','3'] 3 3
// str[....index-1]绕娘,按出的結(jié)果是什么都在path里
// str[index...] 按完之后,有哪些組合晓猛,放入到ans里
public static void process(char[] str, int index, char[] path, List<String> ans) {
if (index == str.length) {
ans.add(String.valueOf(path));
} else {
char[] cands = phone[str[index] - '2'];
for (char cur : cands) {
path[index] = cur;
process(str, index + 1, path, ans);
}
}
}
}
image-20210426085146937