当前位置:网站首页>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());
}
};
边栏推荐
- vim common operation commands
- C# 动态加载卸载 DLL
- Workaround without Project Facets
- [in-depth study of 4 g / 5 g / 6 g project - 50] : URLLC - 16 - the 3 GPP URLLC agreement, specification, technical principle of depth interpretation - 10 - high reliability technology - 1 - low codin
- 【HMS core】【Media】【视频编辑服务】 在线素材无法展示,一直Loading状态或是网络异常
- 如何通过使用“缓存”相关技术,解决“高并发”的业务场景案例?
- MySQL性能指标TPS\QPS\IOPS如何压测?
- B.构造一个简单的数列(贪心)
- 考研上岸又转行软件测试,从5k到13k完美逆袭,杭州校区小哥哥拒绝平庸终圆梦!
- Set partition minimum difference problem (01 knapsack)
猜你喜欢
随机推荐
Android Sqlite3 basic commands
在腾讯,我的试用期总结!
How to automatically renew the token after it expires?
爬虫——selenium基本使用、无界面浏览器、selenium的其他用法、selenium的cookie、爬虫案例
2042. 检查句子中的数字是否递增-力扣双百代码-设置前置数据
如何在ubuntu环境下安装postgresql并配置远程访问
OAID是什么
南瓜科学产品升级 开启益智探索新篇章
G.登山小分队(暴力&dfs)
How to install postgresql and configure remote access in ubuntu environment
Sum of four squares, laser bombs
【Web技术】1401- 图解 Canvas 入门
七夕邂逅爱,那人一定在
[深入研究4G/5G/6G专题-50]: URLLC-16-《3GPP URLLC相关协议、规范、技术原理深度解读》-10-高可靠性技术-1-低编码率编码调制方案MCS与高可靠性DRB
Kyushu Cloud attended the Navigator Online Forum to discuss the current status, challenges and future of 5G MEC edge computing
Keycloak 6.0.0 正式发布,身份和访问管理系统
xpath获取带命名空间节点注意事项
小 P 周刊 Vol.13
Oracle RAC环境下vip/public/private IP的区别
metaRTC5.0新版本支持mbedtls(PolarSSL)









