给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。 2 3 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。 4 5 6 7 8 9 示例: 10 11 输入:"23" 12 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 13 14 来源:力扣(LeetCode) 15 链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number 16 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 17 18 19 20 public class Leetcode17 { 21 //定义一个map集合用于记录数字键对应的字母 22 Map<String, String> phone = new HashMap<String, String>() {{ 23 put("2", "abc"); 24 put("3", "def"); 25 put("4", "ghi"); 26 put("5", "jkl"); 27 put("6", "mno"); 28 put("7", "pqrs"); 29 put("8", "tuv"); 30 put("9", "wxyz"); 31 }}; 32 //定义一个成员变量用于存放各种情况的值。 33 List<String> output = new ArrayList<String>(); 34 public static void main(String[] args) { 35 List<String> strings =new Leetcode17().letterCombinations("23"); 36 System.out.println(strings); 37 } 38 //digits用于存放输入的数字 39 public List<String> letterCombinations(String digits) { 40 if (digits.length() != 0) 41 backtrack("", digits); 42 return output; 43 } 44 //递归方法 combination表示已经加起来的临时字符串,next_digits 表示剩余的数字、 45 public void backtrack(String combination, String next_digits) { 46 //递归方法出口,表示其中的一种组合方式拼接完成,存放进结果集中。 47 if (next_digits.length()==0) { 48 output.add(combination); 49 }else { 50 //取剩余没遍历的数字中的第一位 51 String digit = next_digits.substring(0,1); 52 //取得数字对应的所有字符 53 String letters = phone.get(digit); 54 //遍历字符,length()是String的一个方法,此方法将String字符串转换为字符数组显示其长度。 55 for (int i = 0; i < letters.length(); i++) { 56 //遍历字符 57 String letter = phone.get(digit).substring(i, i + 1); 58 //递归调用 next_digits.substring(1)表示从第一位到最后一位的所有数字。 59 backtrack(combination+letter,next_digits.substring(1)); 60 61 } 62 } 63 64 } 65 } 66
输入:23
输出:[ad, ae, af, bd, be, bf, cd, ce, cf]
过程是:先取得"23"的第一位数字"2",然后取得对应的字符"abc",然后遍历"abc",继续调用递归函数 backtrack("a","23".substring(1)),所以参数还剩"3",
取得"3"对应的字符"def",然后遍历,在调用递归函数 backtrack("a"+"d","3".substring(1)),此时已经没有剩余的数字,就到了递归的的出口,把"ad"放入
结果集,然后回到上一层的for循环,递归调用 backtrack("a"+"e","3".substring(1))。。。。。