The topic of the classic backtracking (backtracking algorithm). When a topic, there are various combinations of satisfying conditions, and need to list them all, you can consider backtracking. Of course, backtracking is a part of the poor, so when the data is particularly large, inappropriate. For those topics, it may be necessary to do it through dynamic programming.
The idea of this problem is very simple, assuming that the input is "23", 2 corresponds to "ABC", 3 corresponds to "EDF", then we are recursive, we first determine the 2 corresponding to one of the letters (assuming a), and then go to the next layer, the poor lifting 3 corresponds to all the letters, and combined ("AE", "ad", "AF "), when" EDF "is exhausted, return to the previous layer, update the letter B, and then re-enter the next layer. This is the basic idea of backtracing.
The code is as follows:
1 Public classSolution {2 PublicList<string>lettercombinations (String digits) {3 //list the letters corresponding to the numbers on the table, and when the input is 2, digits[2] is 2 of the corresponding "ABC"4string[] Table =Newstring[]5{"", "", "abc", "Def", "Ghi", "JKL", "MnO", "PQRS", "TUV", "WXYZ"};6list<string> list =NewArraylist<string>();7 //Index starting at 0, i.e. the first digit of digits8Lettercombinations (List,digits, "", 0, table);9 returnlist;Ten } One A Private voidLettercombinations (list<string>list, String digits, -String Curr,intindex,string[] table) { - //last level exit condition the if(Index = =digits.length ()) { - if(Curr.length ()! = 0) List.add (curr); - return; - } + - //find the string corresponding to the number +String temp = Table[digits.charat (index)-' 0 ']; A for(inti = 0; I < temp.length (); i++) { at //each time the loop adds a different string to the current Curr -String Next = Curr +Temp.charat (i); - //go to the next level -Lettercombinations (list,digits,next,index+1, table); - } - } in}
Leetcode (+)-letter combinations of a Phone number