根据输入数字按手机九建求可能组合成的字符串(leetcode17):
Given a string containing digits from 2-9
inclusive, 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. Note that 1 does not map to any letters.
Example:
Input: "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
思路:按序拆分数字字符串,每个数字字符对应多个字符,所以要遍历对应的每个字符,拼接到结果字符串,在此基础上再遍历一个数字字符对应的每个字母字符,拼接到结果字符串上,这就是一个递归的过程,递归的出口就是遍历完所有的数字字符。如图所示:
当遍历到数字字符2时,对于其对应的每个字母字符,都要拼接到结果字符上(res)同时递归调用遍历下一个数字字符3,整个递归过程的出口就是数字字符已经遍历完了,即下标大于length。
class Solution {
List<String> res = new ArrayList<String>();
final static String[] letterMap = {" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public List<String> letterCombinations(String digits) {
if(digits.equals("")){
return res;
}
return helper(digits,0,"");
}
//index 当前数字字符串下标
public List<String> helper(String digits, int index, String currStr){
if(index == digits.length() ){
res.add(currStr);
return res;
}
//找到当前数字
char c = digits.charAt(index);
//找到当前数字对应的字符串
String letter = letterMap[c-'0'];
//挨个遍历、递归组合字符串
for(int i = 0; i < letter.length(); i++){
helper(digits, index+1, currStr+letter.charAt(i));
}
return res;
}
}