Topic:
Given a digit string, return all possible letter combinations, the number could represent.
A mapping of Digit to letters (just as on the telephone buttons) is given below.
Input: Digit string "Output": ["Ad", "AE", "AF", "BD", "Be", "BF", "CD", "CE", "CF"].
Note:
Although the above answer is in lexicographical order, your answer could are in any order you want.
Ideas:
- In fact, it is necessary to traverse all possible, from each number corresponding to the letter selected, together, if the use of brute force enumeration, it is really difficult to engage and will time out;
- Recursion, the key is to find the rules, the rules are as follows:
digits-number String I -number string subscript temp-Temporary string res-return value public void Dfs (string digits, int i, String temp, list<string > Res)
- initial conditions: start with the first digit of the number string, define the temporary string" ", define the list to be returned, start recursion, dfs (digits, 0," ", res) ;
- If the number string is finished, return to list, otherwise get the string corresponding to the number, traverse each letter, add to the temporary string, and start with the next digit of the number string, recursive call, DFS (digits, i+1, TEMP2, res);
Import Java.util.arraylist;import Java.util.hashmap;import Java.util.list;public class Lettercombinations {HashMap <integer, string> map = new Hashmap<integer, string> () {put (0, "");p ut (1, "");p ut (2, "ABC");p ut (3, "def");p u T (4, "GHI");p ut (5, "JKL");p ut (6, "MNO");p ut (7, "PQRS");p ut (8, "TUV");p UT (9, "WXYZ");}; Public list<string> lettercombinations (String digits) {list<string> res = new arraylist<> ();d FS ( Digits, 0, "", res); return res; } digits-number String I -number string subscript temp-Temporary string res-return value public void Dfs (string digits, int i, String temp, list<string > Res) {if (i = = Digits.length ()) {Res.add (temp); return;} string s = Map.get (Digits.charat (i)-' 0 '), for (int j=0; j< s.length (); j + +) {String Temp2 = temp +s.charat (j);d FS (digits, I+1, Temp2, res);}}}
Leetcode | #17 letter combinations of a Phone number