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"].
Idea: If the string length is known, the direct use of multi-cycle efficiency is higher. However, the length of the problem is unknown, using recursion, a layer of recursion to go down, this idea is very important, and finally need to be careful to check the special case null and "".
PublicList<string>lettercombinations (String digits) {List<String> list=NewArraylist<string>(); if(digits==NULL|| Digits.length () ==0) returnlist; Digits=digits.replace ("1", "" "); Map<character, string> map=NewHashmap<character,string>(); Map.put (' 1 ', ""); Map.put (' 2 ', ' abc '); Map.put (' 3 ', "Def"); Map.put (' 4 ', "Ghi"); Map.put (' 5 ', "JKL"); Map.put (' 6 ', "MNO"); Map.put (' 7 ', "PQRS"); Map.put (' 8 ', "TUV"); Map.put (' 9 ', "WXYZ"); Map.put (' 0 ', ""); RECURSESTR (map, digits,0, List, ""); returnlist; } Private voidRECURSESTR (map<character,string> map,string digits,intDepth,list<string>list,string Re) { if(depth==digits.length ()) {List.add (re); return; } String Temp=Map.get (Digits.charat (depth)); for(intI=0;i<temp.length (); i++) {recursestr (map,digits,depth+1, List, re+Temp.charat (i)); } }
[Leetcode] letter combinations of a Phone number