Problem:
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"].
The problem is that given a string of numbers, all combinations of these numbers correspond to the letters on the phone keys. We consider using dynamic programming to solve this problem. Suppose that the numbers in this string are C1, C2, ..., Cn, total n numbers, and now consider whether you can turn this problem into a smaller, but similar, problem, when a given string contains C1, C2, ..., Cn-1, the letter combination of the first n-1 numbers, How to find a combination of letters plus a number
Take the number string "23" for example, assuming that the "2" corresponding to the letter combination of {"A", "B", "C"}, then how to find the "23" corresponding to the letter combination? Can be from the collection {"A", "B", "C"} each time a string is taken, and then 3 corresponding to the three letters D, E, F are stitched into a new string, so that the "23" corresponding to all the letter combination, {"ad", "AE", "AF", "BD", "Be", "BF", " CD "," CE "," CF "}.
The initial problem can be solved by extending the above-mentioned simple situation to the general situation. Starting with the collection containing an empty string {""}, in order from left to right, from C1, C2,..., cn each time a number is taken, each letter of CI corresponding to each string in the collection is stitched together to get a new set of strings, followed by a round of ci+ The 1 stitching is then based on this new collection.
The Java implementation algorithm is as follows:
1 Public classSolution1 {2 PublicList<string>lettercombinations (String digits) {3string[] Mapping =Newstring[]{"", "", "abc", "Def", "Ghi", 4"JKL", "MnO", "PQRS", "TUV", "WXYZ"};5List<string> lastlist =NewArraylist<string>();6 if(Digits = =NULL|| Digits.length () = = 0) {7 returnlastlist;8 }9Lastlist.add ("");TenList<string> worklist =NewArraylist<string>(); One for(inti = 0; I < digits.length (); i++) { A intdigit =Integer.parseint (string.valueof (Digits.charat (i))); - for(String str:lastlist) { - for(intj = 0; J < Mapping[digit].length (); J + +) { theStringBuilder SB =NewStringBuilder (str); - Sb.append (Mapping[digit].charat (j)); - Worklist.add (sb.tostring ()); - } + } - +list<string> tmp =lastlist; ALastlist =worklist; atWorklist =tmp; - - worklist.clear (); - } - - returnlastlist; in } -}
[Leetcode] Letter combinations of a Phone number