leetcode 0017
说明
只是为了记录一下,不求多快,也不深究。
会简要描述思路,代码中不写注释。
如碰到不会做的用了别人代码会在博客中标出。
题目描述
结果
参考
【LeetCode/算法】油管上最好的Java 版本 LeetCode逐题详解
思路
猜到了是遍历树,但是不知道怎么写了,数据结构不过关,还是要多练的,不然太菜了。
就是一个深搜。
代码
class Solution {
public List<String> letterCombinations(String digits) {
if(digits == null||digits.length() == 0) {
return new ArrayList<String>();
}
List<String> ls = new ArrayList<String>();
Map<Character,char[]> map = new HashMap<Character, char[]>();
map.put('2', new char[] {'a','b','c'});
map.put('3', new char[] {'d','e','f'});
map.put('4', new char[] {'g','h','i'});
map.put('5', new char[] {'j','k','l'});
map.put('6', new char[] {'m','n','o'});
map.put('7', new char[] {'p','q','r','s'});
map.put('8', new char[] {'t','u','v'});
map.put('9', new char[] {'w','x','y','z'});
dfs("", 0, map, ls, digits);
return ls;
}
public void dfs(String curr,int currIdx,Map<Character,char[]> map,List<String> ls,String digits) {
if(currIdx == digits.length()) {
ls.add(curr);
return;
}
Character c = digits.charAt(currIdx);
if(map.containsKey(c)) {
for(char ch: map.get(c)) {
dfs(curr+ch,currIdx+1,map,ls,digits);
}
}
}
}