版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Neo233/article/details/83036587
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.
这个题使用的迭代法,不断的迭代list中的元素进行新元素的添加,方法挺奇妙
1)
class Solution {
public List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<>();
String[] a = new String[]{" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
for(int i = 0 ; i < digits.length() ; i++){
char[] arr = a[digits.charAt(i) - '0'].toCharArray();
List<String> li = new ArrayList<>();
if(list.isEmpty()){
list.add("");
}
for(String s : list){
for(int j = 0 ; j < arr.length;j++){
li.add(s + arr[j]);
}
}
list = li;
}
return list;
}
}
2)
public class Solution {
List<String> res;
public List<String> letterCombinations(String digits) {
// 建立映射表
String[] table = {" ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
StringBuilder tmp = new StringBuilder();
res = new LinkedList<String>();
helper(table, 0, tmp, digits);
return res;
}
private void helper(String[] table, int idx, StringBuilder tmp, String digits){
if(idx == digits.length()){
// 找到一种结果,加入列表中
if(tmp.length()!=0) res.add(tmp.toString());
} else {
// 找出当前位数字对应可能的字母
String candidates = table[digits.charAt(idx) - '0'];
// 对每个可能字母进行搜索
for(int i = 0; i < candidates.length(); i++){
tmp.append(candidates.charAt(i));
helper(table, idx+1, tmp, digits);
tmp.deleteCharAt(tmp.length()-1);
}
}
}
}
假设总共有n个digit,每个digit可以代表k个字符,那么时间复杂度是O(k^n),就是结果的数量,空间复杂度也是一样