https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
This code is to generate all possible strings, when each digit between 2 to 9 (inclusive) are mapped to English alphabet string.
The question is to recreate mobile phone T9 dictionary, which means, if user types 23, then all possible combinations of strings of "abc" and "def" should be returned.
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(letterCombinations("23"));
}
private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
public static List<String> letterCombinations(String digits) {
List<String> ret = new LinkedList<String>(); //this is the local variable.
combination("", digits, 0, ret); //being sent to a method. But that method doesn't have any return type.
return ret; //so, how is this ret being populated????
}
private static void combination(String prefix, String digits, int offset, List<String> ret) {
if (offset >= digits.length()) {
ret.add(prefix);
return;
}
String letters = KEYS[(digits.charAt(offset) - '0')];
for (int i = 0; i < letters.length(); i++) {
combination(prefix + letters.charAt(i), digits, offset + 1, ret);
}
}
}
How does the ret
declared and instantiated within letterCombination()
method gets set, when combination( )
method doesn't have a return type.