我的做法是利用迭代来代替递归
本质这个是一个尾递归结构,跟数数是一个道理
public class Solution {
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<>();
int[] digitCount = new int[10];
for (int i = 0; i< 10 ; i++) {
digitCount[i] = 0;
}
int length = digits.length();
for (int i = 0; i < length; i++) {
int d = digits.charAt(i) - 48;
digitCount[d] = digitCount[d] + 1;
}
if (digitCount[0] > 0 || digitCount[1] > 0) {
return result;
}
List<Integer> digitArray = new ArrayList<>();
for (int i = 0; i<digits.length();i++) {
digitArray.add(digits.charAt(i)-48);
}
List<Character> char2 = Arrays.asList('a', 'b', 'c');
List<Character> char3 = Arrays.asList('d', 'e', 'f');
List<Character> char4 = Arrays.asList('g', 'h', 'i');
List<Character> char5 = Arrays.asList('j', 'k', 'l');
List<Character> char6 = Arrays.asList('m', 'n', 'o');
List<Character> char7 = Arrays.asList('p', 'q', 'r', 's');
List<Character> char8 = Arrays.asList('t', 'u', 'v');
List<Character> char9 = Arrays.asList('w', 'x', 'y', 'z');
List<List<Character>> charMap = new ArrayList<List<Character>>();
charMap.add(char2);
charMap.add(char3);
charMap.add(char4);
charMap.add(char5);
charMap.add(char6);
charMap.add(char7);
charMap.add(char8);
charMap.add(char9);
int[] pointer = new int[digitArray.size()];
for (int i = 0; i< digitArray.size();i++) {
pointer[i]=0;
}
int p = digitArray.size()-1;
while(p >= 0) {
if (p == digitArray.size()-1 && pointer[digitArray.size()-1] < charMap.get(digitArray.get(digitArray.size()-1)-2).size()) {
char[] resultChars = new char[digitArray.size()];
for (int i=0;i<digitArray.size();i++){
resultChars[i]=charMap.get(digitArray.get(i)-2).get(pointer[i]);
}
String resultString = new String(resultChars);
result.add(resultString);
pointer[p]++;
continue;
}
if (pointer[p] == charMap.get(digitArray.get(p)-2).size()) {
p--;
if (p<0)
break;
pointer[p]++;
} else {
for (int i = p+1; i < digitArray.size(); i++) {
pointer[i] =0;
}
p=digitArray.size()-1;
}
}
return result;
}
}
看到更加优雅的一个解法
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<String>();
if(digits.isEmpty()) {
result.add("");
return result;
}
String[] map = new String[10];
map[0] = "";
map[1] = "";
map[2] = "abc";
map[3] = "def";
map[4] = "ghi";
map[5] = "jkl";
map[6] = "mno";
map[7] = "pqrs";
map[8] = "tuv";
map[9] = "wxyz";
int[] number = new int[digits.length()]; //存储digits中每个字符在循环中的编号,初始为0
int k = digits.length()-1;
while(k>=0) {
k = digits.length()-1;
char[] charTemp = new char[digits.length()];
for(int i=0; i<digits.length(); i++) {
charTemp[i] = map[digits.charAt(i)-'0'].charAt(number[i]);
}
result.add(new String(charTemp));
while(k>=0) {
if( number[k] < (map[digits.charAt(k)-'0'].length()-1) ) {
number[k]++;
break;
} else {
number[k] = 0;
k--;
}
}
}
return result;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。