当前位置:网站首页>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());
}
};
边栏推荐
- 量化细胞内的信息流:机器学习时代下的研究进展
- 考研上岸又转行软件测试,从5k到13k完美逆袭,杭州校区小哥哥拒绝平庸终圆梦!
- CCF GLCC正式开营|九州云开源专家携丰厚奖金,助力高校开源推广
- Makefile 语法及使用笔记
- centos7安装mysql急速版
- 记录都有哪些_js常用方法总结
- Rust 从入门到精通04-变量
- B. Construct a simple sequence (greedy)
- idea去掉spark的日志
- [Beiya data recovery] IBM System Storage storage lvm information lost data recovery solution
猜你喜欢
随机推荐
Android Sqlite3 basic commands
Execution failed for task ‘:xxx:generateReleaseRFile‘.
基于 Next.js实现在线Excel
【剑指offer33】二叉搜索树的后序遍历序列
【北亚数据恢复】IBM System Storage存储lvm信息丢失数据恢复方案
CCF GLCC officially opened | Kyushu Cloud open source experts bring generous bonuses to help universities promote open source
Chinese valentine's day, of course, to learn SQL optimization better leave work early to find objects
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
Qt的QItemDelegate使用
记录都有哪些_js常用方法总结
节省50%成本!京东云重磅发布新一代混合CDN产品
手搓一个“七夕限定”,用3D Engine 5分钟实现烟花绽放效果
Redis 复习计划 - Redis主从数据一致性和哨兵机制
How to write SQL statements: the usage of Update, Case, and Select together
谷歌插件.crx文件下载后被自动删除的解决方法
JCMsuite应用:倾斜平面波传播透过光阑的传输
Keycloak 6.0.0 正式发布,身份和访问管理系统
eNSP-小型网络拓扑(DNS、DHCP、网站服务器、无线路由器)
Makefile 语法及使用笔记
B.构造一个简单的数列(贪心)