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.
Problem Solving Ideas:
Using the DFS algorithm, the Java implementation is as follows:
Static string[] Alpha = new string[] { "", "1", "abc", "Def", "Ghi", "JKL", "MnO", "PQRS", "TUV", "WXYZ" }; static StringBuilder sb = new StringBuilder (); static void Dfs (list<string> List, String digits, int cur) { if (cur >= digits.length ()) List.add ( Sb.tostring ()); else {for (int i = 0; i < Alpha[digits.charat (cur)-' 0 '].length (); i++) { sb.append (Alpha[digits.charat (cur) -' 0 '].charat (i)); DFS (list, digits, cur + 1); Sb.deletecharat (Sb.length ()-1); }}} static public list<string> lettercombinations (String digits) { list<string> List = new arraylist< String> (); if (Digits.length () ==0) return list; DFS (list, digits, 0); return list; }
Idea two:
Wherever recursion is used, it can be solved using loops, so the Java implementation is as follows:
static public list<string> lettercombinations (String digits) {list<string> List = new arraylist< String> (); String[] Alpha = new string[] {"", "1", "abc", "Def", "Ghi", "JKL", "MnO", "PQRS", "TUV", "WXYZ"}; if (Digits.length () ==0) return list; int[] Number = new Int[digits.length ()];//store each traversal character position int index = 0; while (index>=0) {StringBuilder sb = new StringBuilder (); for (int i=0; i<digits.length (); i++) Sb.append (Alpha[digits.charat (i)-' 0 '].charat (number[i])); List.add (Sb.tostring ()); Each turn needs to be reset index to the end of index = Digits.length ()-1; while (index>=0) {if (Number[index] < (Alpha[digits.charat (index)-' 0 '].length ()-1)) { number[index]++; Break } else {Number[index] = 0; index--; } }} return list; }
Java for Leetcode 017 letter combinations of a Phone number