给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 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']
的一个数字。
Related Topics
题解
看到题目第一印象是遍历多重循环,然后想了下好像不对,给定的字符串长度不定,瞅了一眼评论区,基本都是回溯,emmmmmmm
想玩点花的,突然想到之前有做过一个转盘锁的,于是计上心来,动手开始撸,
直白点的说明的话,就是说,从[0,0,0,0.....,0]枚举到[3,3,4,3,....4]这样的组合
class Solution {
private char[][] map = new char[][]{
{97,98,99,0}, {100,101,102,0},
{103,104,105,0}, {106,107,108,0}, {109,110,111,0},
{112,113,114,115},{116,117,118,0}, {119,120,121,122}
};
public List<String> letterCombinations(String digits) {
// String n = "0123456789";//48-57
char[] nCharArr = digits.toCharArray();
int charLength = nCharArr.length;
if (charLength ==0){
return new ArrayList<>();
}
int count = 1;
for (char c : nCharArr) {
if (map[c-50][3]==0){
count = count * 3;
}else{
count = count * 4;
}
}
char[][] res = new char[count][charLength];
int[] stepCount = new int[charLength];
Arrays.fill(stepCount,0);
for (int i = 0; i < count; i++) {
for (int j = 0; j < stepCount.length; j++) {
res[i][j] = map[nCharArr[j]-50][stepCount[j]];
}
stepInc( nCharArr, stepCount );
}
List<String> resList = new ArrayList<>();
for (char[] re : res) {
resList.add(new String(re));
}
// System.out.println(res);
return resList;
}
private void stepInc(char[] nCharArr, int[] stepCount){
boolean willPlus = true;
for (int i = 0; i < stepCount.length; i++) {
int index = stepCount.length - i - 1;
if (willPlus){
stepCount[index] = stepCount[index]+1;
if(map[nCharArr[index]-50][3]==0){
//满3进
if (stepCount[index]==3){
stepCount[index]=0;
}else{
willPlus = false;
}
}else{
//满4进
if (stepCount[index]==4){
stepCount[index]=0;
}else{
willPlus = false;
}
}
}
}
}
}
写完跑了下,居然过了,差点被自己笑到。。。
发表评论