Letter combinations of a Phone number
Problem:
Iven 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.
Ideas:
dfs+ Backtracking
My Code:
Public classSolution { PublicList<string>lettercombinations (String digits) {List<String> list =NewArraylist<string>(); if(Digits = =NULL|| Digits.length () = = 0)returnlist; Helper ("", digits, list); returnlist; } Public voidHelper (string s, string digits, list<string>list) { if(digits.length () = = 0) {List.add (s); return; } Chardigit = Digits.charat (0); String Letters=getletters (digit); if(Letters.equals ("") {Helper (S, digits.substring (1), list); } for(inti = 0; I <letters.length (); i++) {Helper (S+letters.charat (i), digits.substring (1), list); } } PublicString Getletters (Charc) {Switch(c) { Case' 2 ':return"ABC"; Case' 3 ':return"DfE"; Case' 4 ':return"Ghi"; Case' 5 ':return"JKL"; Case' 6 ':return"MnO"; Case' 7 ':return"PQRS"; Case' 8 ':return"TUV"; Case' 9 ':return"WXYZ"; default:return""; } }}
View Code
Others code:
Public classSolution { PublicArraylist<string>lettercombinations (String digits) {ArrayList<String> result =NewArraylist<string>(); if(Digits = =NULL) { returnresult; } Map<character,Char[]> map =NewHashmap<character,Char[]>(); Map.put (' 0 ',New Char[] {}); Map.put (' 1 ',New Char[] {}); Map.put (' 2 ',New Char[] {' A ', ' B ', ' C ' }); Map.put (' 3 ',New Char[] {' d ', ' e ', ' F ' }); Map.put (' 4 ',New Char[] {' G ', ' h ', ' I ' }); Map.put (' 5 ',New Char[] {' J ', ' K ', ' l ' }); Map.put (' 6 ',New Char[] {' m ', ' n ', ' O ' }); Map.put (' 7 ',New Char[] {' P ', ' Q ', ' R ', ' s ' }); Map.put (' 8 ',New Char[] {' t ', ' u ', ' V '}); Map.put (' 9 ',New Char[] {' W ', ' x ', ' y ', ' z ' }); StringBuilder SB=NewStringBuilder (); Helper (map, digits, SB, result); returnresult; } Private voidHelper (Map<character,Char[]>map, String digits, StringBuilder sb, ArrayList<String>result) { if(sb.length () = =digits.length ()) {Result.add (sb.tostring ()); return; } for(CharC:map.get (Digits.charat (Sb.length ()))) {sb.append (c); Helper (map, digits, SB, result); Sb.deletecharat (Sb.length ()-1); } }}
View Code
The Learning Place:
- String self-tracing property This aspect reduces a lot of problems constantly new s consumption of space is still quite a lot.
- In other people's code is StringBuffer relative, save space.
Letter combinations of a Phone number