真是一道好题。
一眼看过去,一想,是bfs
; 然后因为是combination
类:典型的dfs
.
bfs
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public List<String> letterCombinations(String digits) { String[] mapping = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; LinkedList<String> res = new LinkedList<>(); if (digits.length() == 0) return res; res.add(""); while (res.peek().length() != digits.length()) { String tmp = res.poll(); String add = mapping[digits.charAt(tmp.length()) - '0']; for (char c : add.toCharArray()) { res.add(tmp + c); } } return res; }
|
res.add("")
是为了启动while
,如果没有就直接return了
dfs
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| private static final String[] mapping = new String[]{"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public List<String> letterCombinations(String digits) { LinkedList<String> res = new LinkedList<>(); combination("", digits, 0, res); return res; }
public void combination(String prefix, String digits, int i, LinkedList<String> res) { if (digits == null || digits.length() == 0) return; if (prefix.length() >= digits.length()) { res.add(prefix); return; } String tmp = mapping[digits.charAt(i) - '0']; for (char c : tmp.toCharArray()) { combination(prefix+c, digits, i+1, res); } }
|
复习static
修饰成员变量: 成员变量属于类对象,而不是哪一个具体的实例对象
复习LinkedList
和纯粹List
方法的不同: 有的对象声明为List
类型, 即使多态右边new对象是LinkedList
,还是会因为左边本身的类型是List
而不能用那个方法。
List
: add
, get
, isEmpty
, remove
, size
LinkedList
: add
, addFirst
, addLast
, getFirst
, getLast
, offer
, peek
, poll
, remove
, push
, size
(也就是Queue
的方法的几个方法都是只有LinkedList
独有而List
没有, 毕竟LinkedList
是Queue
的实现类)