Leetcode1-100: 17. Letter Combinations of a Phone Number
问题描述
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
这题的意思是给出电话号码的字典,输入一个数字串,给出可能的所有字符串输出集合。类似于中文输入法输入几个数字得出可能的字母组合结果。
解题思路
- 直接按照接替思路来做,每次取一个数字,把所有对应的字符append刀前面然后加入到结果集合中
- 递归法。保存当前暂存的结果,然后append新的字符,长度不够的时候不需要加入结果集合中,当字符串长度足够了之后就加入到结果集合中。
代码实现
implement 1. Brute force
public List<String> letterCombinations(String digits) {
String[] dict = new String[]{"", "", "abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
if(digits.length() == 0)
return new LinkedList<String>();
LinkedList<String> res = new LinkedList<>();
for(int i = 0; i < digits.length(); i++) {
if(res.isEmpty()) {
for(int j = 0; j < dict[digits.charAt(i) - '0'].length(); j++)
res.add(String.valueOf(dict[digits.charAt(i) - '0'].charAt(j)));
} else {
LinkedList<String> tmp = new LinkedList<>();
for(int j = 0; j < dict[digits.charAt(i) - '0'].length(); j++) {
for(int k = 0; k < res.size(); k++) {
tmp.add(String.valueOf(res.get(k)+dict[digits.charAt(i) - '0'].charAt(j)));
}
}
res = tmp;
}
}
return res;
}
可以看出来,时间复杂度比较高。
implement 2. 递归法
public List<String> letterCombinations(String digits) {
String[] dict = new String[]{"", "", "abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
if(digits.length() == 0)
return new LinkedList<String>();
LinkedList<String> res = new LinkedList<>();
combination(res, "", 0, digits, dict);
return res;
}
public void combination(List<String> res, String tmp, int offset, String digits, String[] dict) {
if(offset == digits.length()) {
res.add(tmp);
} else {
char c = digits.charAt(offset);
String candidates = dict[c - '0'];
for(int i = 0; i < candidates.length(); i++) {
String s =tmp + String.valueOf(candidates.charAt(i));
combination(res, s, offset+1, digits, dict);
}
}
}
复杂度分析
对于实现1的brute force方法,时间复杂度是O(4N*3M),其中N是对应着4个字符的数字个数(也可以写成O(4N+M)),M是对应着3个字符的数字个数, 空间复杂度是O(4N*3M)
对于实现2的递归方法, 由
for(int i = 0; i < candidates.length(); i++) {
String s =tmp + String.valueOf(candidates.charAt(i));
combination(res, s, offset+1, digits, dict);
}
可以得到TN = 4 * TN-1 (简写,实际有的是三倍有的是四倍),所以最后的时间复杂度和空间复杂度都跟方法一一样的是O(4N*3M)
分析
关于递归算法的复杂度计算比较绕,但是很暴力的一种方法就是直接通过代码来找到TN和TN-1之间的关系之后就很好计算了。详情见这里