题目描述:
Given a digit string, 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.
Input:Digit string "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.
思路解析:
- digit表示给出的数字键,依次遍历每个数字,可以使用递归
- 可以使用StringBuilder表示输出的一个字符串,如果这个字符串的长度已经等于给出的数字字符串长度,那么就结束递归。
- 把每个数字对应的字符串列出来,然后每次都去遍历
- 注意每次加上一个字符的时候,递归后边的字符以后,还要把最后一个字符去掉。保持完整
代码:
import java.util.*;
public class Solution {
public ArrayList<String> letterCombinations(String digits) {
ArrayList<String> res = new ArrayList<String>();
if(digits==null)
return res;
String[] keyboard = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
StringBuilder current = new StringBuilder();
int index =0;
helper(index,digits,res,current,keyboard);
return res;
}
public void helper(int index,String digits,ArrayList<String> res,StringBuilder current,String[] keyboard){
if(index==digits.length()){
res.add(current.toString());
return;
}
int num = digits.charAt(index)-'0';
for(int i=0;i<keyboard[num].length();i++){
current.append(keyboard[num].charAt(i));
helper(index+1,digits,res,current,keyboard);
current.deleteCharAt(current.length()-1);//保证 可以加入本数字表示的下个字符
}
}
}