问题:
难度:medium
说明:
按照平时的电话号码来按按键,获得对应的字母,那么平时的电话按键是这样的:
1 - "" 2 - "abc" 3 - "def"
4 - "ghi" 5 - "jkl" 6 - "mno"
7 - "pqrs" 8 - "tuv" 9 - "wxyz"
那么输入如果是 23 就是按了 2 3 对应的电话按钮,会出现2 和 3 两个按钮的字母组合,如案例展示。其中 1 是什么都没有
题目连接:https://leetcode.com/problems/letter-combinations-of-a-phone-number/
输入范围:
0 <= digits.length <= 4
digits[i]
is a digit in the range['2', '9']
.
输入案例:
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"]
我的代码:
做下复习,这个是需要一个暴力深搜就可以的了,本来也就最多 4 个数字,小心下 1 就好,1 也算输入不过为空,还有如果输入是 "" 那么应该是返回空集合。
Java:
class Solution {
private static char[][] cacheMap = new char[8][];
static {
cacheMap[0] = new char[]{'a', 'b', 'c'};
cacheMap[1] = new char[]{'d', 'e', 'f'};
cacheMap[2] = new char[]{'g', 'h', 'i'};
cacheMap[3] = new char[]{'j', 'k', 'l'};
cacheMap[4] = new char[]{'m', 'n', 'o'};
cacheMap[5] = new char[]{'p', 'q', 'r', 's'};
cacheMap[6] = new char[]{'t', 'u', 'v'};
cacheMap[7] = new char[]{'w', 'x', 'y', 'z'};
}
public List<String> letterCombinations(String digits) {
if(digits == null || digits.length() == 0) return Collections.EMPTY_LIST;
List<String> res = new ArrayList<String>();
recurtion(digits.toCharArray(), 0, new StringBuilder(), res, digits.length());
return res;
}
public void recurtion(char[] chs, int index, StringBuilder builder, List<String> res, int len) {
if(index == len) {
res.add(builder.toString());
return;
}
int num = chs[index] - '2';
if(num >= 0) {
char[] arr = cacheMap[num];
for(int i = 0, arrLen = arr.length; i < arrLen; i ++) {
builder.append(arr[i]);
recurtion(chs, index + 1, builder, res, len);
builder.setLength(builder.length() - 1);
}
}
else
recurtion(chs, index + 1, builder, res, len);
}
}
C++:
指针有点难理解
class Solution {
public:
vector<string> letterCombinations(string digits) {
if (!digits.size()) return {};
char cacheMap[8][4] = { { 'a', 'b', 'c' },{ 'd', 'e', 'f' } ,{ 'g', 'h', 'i' },
{ 'j', 'k', 'l' },{ 'm', 'n', 'o' },{ 'p', 'q', 'r', 's' },
{ 't', 'u', 'v' },{ 'w', 'x', 'y', 'z' } };
vector<string> res;
string builder(digits);
recurtion(res, digits, 0, 0, digits.size(), builder, cacheMap);
return res;
}
void recurtion(vector<string> &res, string digits, int index, int strLen, int len, string builder, char cacheMap[8][4]) {
if (index == len) {
res.push_back(builder.substr(0));
return;
}
int num = digits[index] - '2';
if (num >= 0) {
char *chs = cacheMap[num];
for (int i = 0; i < 4; i++) {
if (chs[i]) {
builder[strLen] = chs[i];
recurtion(res, digits, index + 1, strLen + 1, len, builder, cacheMap);
}
}
}
else {
recurtion(res, digits, index + 1, strLen, len, builder, cacheMap);
}
}
};