# algorithm - algorithm - 如何打印出给定电话号码可能代表的所有可能的字母组合？

``````
digit_map = {

'2': 'abc',

'3': 'def',

'4': 'ghi',

'5': 'jkl',

'6': 'mno',

'7': 'pqrs',

'8': 'tuv',

'9': 'wxyz',

}

def word_numbers(input):

input = str(input)

ret = ['']

for char in input:

letters = digit_map.get(char, '')

ret = [prefix+letter for prefix in ret for letter in letters]

return ret

``````

`ret` 是目前为止的结果列表；它最初用一个项填充，空字符串。 然后，对于输入字符串中的每个字符，它会从顶部定义的字典中查找与其匹配的字母列表。 然后，它用现有前缀和可能字母的每个组合替换列表 `ret`

``````
import java.util.HashMap;

public class Solution {

public ArrayList<String> letterCombinations(String digits) {

ArrayList<String> res = new ArrayList<String>();

ArrayList<String> preres = new ArrayList<String>();

for(int i = 0; i <digits.length(); i++) {

String letters = map.get(digits.charAt(i));

if (letters.length() == 0)

continue;

for(String str : res) {

for(int j = 0; j <letters.length(); j++)

}

res = preres;

preres = new ArrayList<String>();

}

return res;

}

static final HashMap<Character,String> map = new HashMap<Character,String>(){{

put('1',"");

put('2',"abc");

put('3',"def");

put('4',"ghi");

put('5',"jkl");

put('6',"mno");

put('7',"pqrs");

put('8',"tuv");

put('9',"wxyz");

put('0',"");

}} ;

}

``````

``````

import java.util.List;

public class Main {

//Number-to-letter mappings in order from zero to nine

public static String mappings[][] = {

{"0"}, {"1"}, {"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"}

};

public static void generateCombosHelper(List<String> combos,

String prefix, String remaining) {

//The current digit we are working with

int digit = Integer.parseInt(remaining.substring(0, 1));

if (remaining.length() == 1) {

//We have reached the last digit in the phone number, so add

//all possible prefix-digit combinations to the list

for (int i = 0; i <mappings[digit].length; i++) {

}

} else {

//Recursively call this method with each possible new

//prefix and the remaining part of the phone number.

for (int i = 0; i <mappings[digit].length; i++) {

generateCombosHelper(combos, prefix + mappings[digit][i],

remaining.substring(1));

}

}

}

public static List<String> generateCombos(String phoneNumber) {

//This will hold the final list of combinations

//Call the helper method with an empty prefix and the entire

//phone number as the remaining part.

generateCombosHelper(combos,"", phoneNumber);

return combos;

}

public static void main(String[] args) {

String phone ="3456789";

List<String> combos = generateCombos(phone);

for (String s : combos) {

System.out.println(s);

}

}

}

``````