Given a string contains only numeric characters 2-9, it can return all letter combinations indicated.
Given digital map to letters as follows (the same telephone key). Note 1 does not correspond to any alphabet.
Example:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/letter-combinations-of-a-phone-number
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
1 determined to contain only numbers 2-9 string, it returns all letter combinations indicated. 2 . 3 gives the following mapping numbers to letters (the same telephone key). Note 1 does not correspond to any alphabet. . 4 . 5 . 6 . 7 . 8 . 9 Example: 10 . 11 Input: "23" 12 Output: [ "ad", "ae ", "af", "bd", "be", "bf", "cd", "ce" , "cf" ]. 13 14 source: stay button (leetCode) 15 links: HTTPS: // leetcode-CN. COM / Problems / Combinations-of-Letter-A-Phone-Number 16 copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source. . 17 18 is . 19 20 is public class Leetcode17 { 21 is // 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 // recursive Combination represented temporary strings have been combined, next_digits represents the remaining figures, 45 public void BackTrack (Combination String, String next_digits) { 46 is // recursive method outlet, which represents a combination splicing is completed, deposited into the result set. 47 IF (next_digits.length () == 0 ) { 48 output.add (Combination); 49 } the else { 50 // number remaining not taken in the first traverse 51 is String digit for next_digits.substring = (0,1 ); 52 // acquired digital corresponding to all of the characters 53 is String Letters = phone.get (digit for); 54 is //Traversing a character, length () is a method of String, String This method string into a character array display its length. 55 for ( int I = 0; I <letters.length (); I ++ ) { 56 is // traversing a character 57 is String Letter = phone.get (digit for) .substring (I, I +. 1 ); 58 // recursive call next_digits .substring (1) represents all numbers from first to last place. 59 BackTrack (+ Combination Letter, next_digits.substring (. 1 )); 60 61 is } 62 is } 63 is 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))。。。。。