【发布时间】:2018-08-29 08:23:50
【问题描述】:
https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
此代码用于生成所有可能的字符串,当 2 到 9(含)之间的每个数字映射到英文字母字符串时。
问题是重新创建手机T9字典,也就是说,如果用户输入23,那么应该返回所有可能的字符串“abc”和“def”的组合。
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);
}
}
}
当combination( ) 方法没有返回类型时,如何在letterCombination() 方法中声明和实例化ret。
【问题讨论】:
-
但是 ret 既不是全局的,combination( ) 也不会返回 "ret" 类型。