212. 单词搜索 II
Java:搜索全部可能,超出时间限制!
class Solution {StringBuilder sb;List<String> list;Set<String> set;private void dfs(int x, int y, int m, int n, char[][] board){if (x < 0 || x >= m || y < 0 || y >= n || board[x][y] == '.') {return;}char ch = board[x][y];sb.append(ch);board[x][y] = '.';if (set.contains(sb.toString())) {list.add(sb.toString());set.remove(sb.toString()); // oaa oa oa 题意没告诉不能重复放入ans}dfs(x + 1, y, m, n, board);dfs(x - 1, y, m, n, board);dfs(x, y + 1, m, n, board);dfs(x, y - 1, m, n, board);board[x][y] = ch;sb.deleteCharAt(sb.length() - 1);}public List<String> findWords(char[][] board, String[] words) {sb = new StringBuilder();list = new ArrayList<>();set = new HashSet<>();for (String str : words) {set.add(str);}int m = board.length, n = board[0].length;for (int i = 0; i < m; ++i) {for (int j = 0; j < n; ++j) {dfs(i, j, m, n, board);}}return list;}
}