Letter combinations of a Phone number
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.
Solution One: Depth First solution
The backtracking method, which searches down until it touches the bottom. This method uses LIFO (LIFO), which is implemented by recursion .
Public classSolution { PublicList<string>lettercombinations (String digits) {LinkedList<String> rst =NewLinkedlist<string>(); if(Digits = =NULL|| Digits.length () = = 0) { returnrst; } string[] Mapping=Newstring[]{"0", "1", "abc", "Def", "Ghi", "JKL", "MnO", "PQRS", "TUV", "WXYZ"};String Temp= ""; Helper (RST, temp, digits, mapping,0); returnrst; } Public voidHelper (list<string> rst, string temp, string digits, string[] mapping,intindex) { if(Index = =digits.length ()) {Rst.add (NewString (temp)); return; } String S=Mapping[character.getnumericvalue (Digits.charat (index))]; for(inti = 0; I < s.length (); i++) {Temp+=S.charat (i); Helper (RST, temp, digits, mapping, index+ 1); Temp= temp.substring (0, Temp.length ()-1); } }}
Solution Two: Breadth First solution
This method uses FIFO (first-in-a-out) and is implemented by non-recursive methods. The Add method that uses the LinkedList data structure is inserted at the end of the list, and the Remove method implements the FIFO by deleting the list header. In addition, the Peek method is used skillfully to update each of the original results each time a new element is added.
Public classSolution { PublicList<string>lettercombinations (String digits) {LinkedList<String> rst =NewLinkedlist<string>(); if(Digits = =NULL|| Digits.length () = = 0) { returnrst; } string[] Mapping=Newstring[]{"0", "1", "abc", "Def", "Ghi", "JKL", "MnO", "PQRS", "TUV", "WXYZ"}; Rst.add (""); for(inti = 0; I < digits.length (); i++) { intm =Character.getnumericvalue (Digits.charat (i)); while(Rst.peek (). Length () = =i) {String s=Rst.remove (); for(CharC:mapping[m].tochararray ()) {Rst.add (S+c); } } } returnrst; }}
It is worth thinking that the second method from the intuitive perspective should run more efficiently, but the actual two methods run at the same time, defeating 46.02% of Java submissions.
Letter combinations of a Phone number: Two solutions for depth first and breadth first