当前位置:网站首页>leetcode:212. 单词搜索 II
leetcode:212. 单词搜索 II
2022-08-04 14:31:00 【OceanStar的学习笔记】
题目来源
题目描述
题目解析
前缀和 + DFS
注意:
- 可能出现: hf、 hfks(易错点)
class Solution {
struct TrieNode{
int size; // 可能出现不止一次
std::string path;
std::vector<TrieNode *> children;
TrieNode() : size(0), children(26, NULL){
}
};
void add(TrieNode *root, std::string &word){
TrieNode *node = root;
for(char ch : word){
int idx = ch - 'a';
if(node->children[idx] == nullptr){
node->children[idx] = new TrieNode();
}
node = node->children[idx];
}
node->size ++;
node->path = word;
}
std::set<std::string> set;
bool process(vector<vector<char>>& board, int i, int j, TrieNode *node){
int N = board.size(), M = board[0].size();
if(i < 0 || j < 0 || i == N || j == M || board[i][j] == 0 || node->children[ board[i][j] - 'a'] == nullptr){
return false;
}
int idx = board[i][j] - 'a';
node = node->children[idx];
if(node->size > 0){
node->size--; // 易错点。。。。。。
set.emplace(node->path);
} //可能还没有结束,不能提前返回
board[i][j] = 0;
bool ans = false;
if(process(board, i + 1, j, node)
|| process(board, i - 1, j, node)
|| process(board, i, j + 1, node)
|| process(board, i, j - 1, node)){
ans = true;
}
board[i][j] = idx + 'a';
return ans;
}
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
TrieNode *root = new TrieNode();
for(auto w : words){
add(root, w);
}
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[i].size(); ++j) {
TrieNode *node = root;
process(board, i, j, node);
}
}
return std::vector<std::string> (set.begin(), set.end());
}
};
边栏推荐
猜你喜欢
16、学习MySQL 正则表达式
自监督学习未来是掩码自编码器?KAIST最新《自监督学习掩码自编码器》研究进展
Bluetooth Technology|In the first half of the year, 1.3 million charging piles were added nationwide, and Bluetooth charging piles will become the mainstream of the market
SLAM 04.视觉里程计-1-相机模型
JCMsuite应用:倾斜平面波传播透过光阑的传输
电子行业MES管理系统有哪些特殊功能
Google plug-in. Download contents file is automatically deleted after solution
metaRTC5.0新版本支持mbedtls(PolarSSL)
X射线掠入射聚焦反射镜
SLAM 05.视觉里程计-2-特征法
随机推荐
小 P 周刊 Vol.13
谷歌插件.crx文件下载后被自动删除的解决方法
没有Project Facets的解决方法
【剑指offer33】二叉搜索树的后序遍历序列
化繁为简,聊一聊复制状态机系统架构抽象
Phasecraft连下两城,助力英国量子技术商业化加速!
【HMS core】【Media】【视频编辑服务】 在线素材无法展示,一直Loading状态或是网络异常
郑轻新生校赛和中工选拔赛题解
CF1527D MEX Tree(mex&树&容斥)
Unity插件:使用PopulationSystem制作行走交流的路人
CF1527D MEX Tree (mex & tree & inclusive)
Android Sqlite3基本命令
Centos7 install mysql version rapidly
快解析结合友加畅捷U+
CCF GLCC officially opened | Kyushu Cloud open source experts bring generous bonuses to help universities promote open source
B. Construct a simple sequence (greedy)
Makefile 语法及使用笔记
用了TCP协议,就一定不会丢包吗?
G.登山小分队(暴力&dfs)
杭电校赛(逆袭指数)