【leetcode】Word Search II(hard)★
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
For example,
Given words = ["oath","pea","eat","rain"]
and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Return ["eat","oath"]
.
思路:
好奇怪啊,我自己写了一个DFS的代码,这种TLE。网上看看发现要用字典树,其实就是把查询给定字符串的过程简化了。
可是我的代码也查询的很容易啊。为什么我的代码TLE,字典树代码就只要56ms呢?
字典数Trie代码:其中标记使用过字符的方式值得学习
class Solution2 {
class Trie{
public:
Trie *children[]; //指向其子序列 从'a'到'z'
bool leaf; //该结点是否是叶子结点
int idx; //如果该节点是叶子结点, idx是该单词在vector中的序号
Trie()
{
this->leaf = false;
this->idx = ;
fill_n(this->children, , nullptr);
}
}; public:
void insertWords(Trie *root, vector<string>& words, int idx)
{
int pos = , len = words[idx].size();
while(pos < len)
{
if(NULL == root->children[words[idx][pos] - 'a'])
root->children[words[idx][pos] - 'a'] = new Trie();
root = root->children[words[idx][pos++] - 'a'];
}
root->leaf = true;
root->idx = idx;
} Trie * buildTrie(vector<string>& words)
{
Trie * root = new Trie();
for(int i = ; i < words.size(); ++i)
insertWords(root, words, i);
return root;
} void checkWords(vector<vector<char>>& board, int i, int j, int row, int col, Trie *root, vector<string> &res, vector<string>& words)
{
if(i < || j < || i >= row || j >= col) return;
if(board[i][j] == 'X') return; //已经访问过
if(NULL == root->children[board[i][j] - 'a']) return;
char temp = board[i][j];
if(root->children[temp - 'a']->leaf) //这是叶子结点
{
res.push_back(words[root->children [temp - 'a']->idx]);
root->children[temp - 'a']->leaf = false; //标为false表示已经找到之歌单词了
}
board[i][j] = 'X'; //标记这个字母为已找过 checkWords(board, i-, j, row, col, root->children[temp-'a'], res, words);
checkWords(board, i+, j, row, col, root->children[temp-'a'], res, words);
checkWords(board, i, j-, row, col, root->children[temp-'a'], res, words);
checkWords(board, i, j+, row, col, root->children[temp-'a'], res, words); board[i][j] = temp;
} vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
vector<string> res;
int row = board.size();
if(==row) return res;
int col = board[].size();
if(==col) return res;
int wordCount = words.size();
if(==wordCount) return res; Trie *root = buildTrie(words); int i,j;
for(i = ; i<row; i++)
{
for(j=; j<col && wordCount > res.size(); j++)
{
checkWords(board, i, j, row, col, root, res, words);
}
}
return res;
} };
我自己的代码:
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
if(board.empty()) return vector<string>(); vector<string> ans;
//对所有入口遍历
for(int i = ; i < board.size(); ++i)
{
for(int j = ; j < board[].size(); ++j)
{
string scur;
unordered_set<int> myset;
getAnswer(i, j, board, words, scur, ans, myset);
}
}
return ans;
} void getAnswer(int i, int j, vector<vector<char>>& MyBoard, vector<string> ResWords, string scur, vector<string>& ans, unordered_set<int> myset)
{
if(ResWords.empty()) return; //没有更多的单词
if(i < || j < || i >= MyBoard.size() || j >= MyBoard[].size()) return;
if(myset.find(i * MyBoard[].size() + j) != myset.end()) return; //该字母已经使用过
myset.insert(i * MyBoard[].size() + j);
vector<string> newResWords;
//对所有剩下待匹配的单词(即前面字母都符合,并且没有完全匹配的单词)
for(int k = ; k < ResWords.size(); ++k)
{
if(MyBoard[i][j] == ResWords[k][scur.length()] && ResWords[k].length() == scur.length() + ) //新字母与单词匹配 且单词没有更多的字母 压入答案
ans.push_back(scur + MyBoard[i][j]);
else if(MyBoard[i][j] == ResWords[k][scur.length()]) //若字母匹配 压入新的剩余单词
newResWords.push_back(ResWords[k]);
}
scur += MyBoard[i][j]; getAnswer(i + , j, MyBoard, newResWords, scur, ans, myset);
getAnswer(i - , j, MyBoard, newResWords, scur, ans, myset);
getAnswer(i, j + , MyBoard, newResWords, scur, ans, myset);
getAnswer(i, j - , MyBoard, newResWords, scur, ans, myset);
}
};
【leetcode】Word Search II(hard)★的更多相关文章
- 【leetcode】Word Ladder II
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation ...
- 【leetcode】Word Break II
Word Break II Given a string s and a dictionary of words dict, add spaces in s to construct a senten ...
- 【leetcode】Word Search
Word Search Given a 2D board and a word, find if the word exists in the grid. The word can be constr ...
- 【leetcode】Word Search (middle)
今天开始,回溯法强化阶段. Given a 2D board and a word, find if the word exists in the grid. The word can be cons ...
- 【leetcode】Word Break II (hard)★
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each ...
- 【leetcode】Word Ladder II(hard)★ 图 回头看
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- Java for LeetCode 212 Word Search II
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
- [LeetCode] 212. Word Search II 词语搜索 II
Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...
- 【LeetCode】47. Permutations II 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:递归 方法二:回溯法 日期 题目地址:htt ...
随机推荐
- WebForm中搭配母版页和用户控件页时候的事件加载顺序
在生产环境中,一个内容页(aspx)可能会包含数个用户控件(ascx),而每个控件可能都会涉及到数据库访问. 如果在内容页.母版页.控件页中各自使用自己的数据库访问方法,会造成很大的运行成本. 这样的 ...
- 如何去各型MCU的官网上下载正确的数据手册
一.背景 感谢老司机左栋,虽然他一直很排斥这个名号 : ) ,可就技术上来说,还是当之无愧的. 弄了1年多单片机了,数据手册不是老员工或者头头给,就是从开发板资料拿.一直没有意识到,官网的东西才是最可 ...
- Mysql InnoDB行锁实现方式
Mysql InnoDB行锁实现方式 InnoDB行锁是通过给索引上的索引项加锁来实现的,这一点MySQL与Oracle不同,后者是通过在数据块中对相应数据行加锁来实现的.InnoDB这种行锁实现特点 ...
- windows server2012和win8安装.netframework3.5失败问题及解决方法
很多人安装windows server2012和Win8后都遇到了无法升级.NET Framework 3.5.1的问题,在线升级会遇到错误0x800F0906.这使得 91手机助手等很多软件无法运行 ...
- ASP.NET发送邮件(QQ发送)
public void SetEmail() { //电子邮件对象 MailMessage mailMessage = new MailMes ...
- Android本地数据存储之SQLite关系型数据库 ——SQLiteDatabase
数据库的创建,获取,执行sql语句: 框架搭建:dao 思考: 1.数据库保存在哪里? 2.如何创建数据库?如何创建表? 3.如何更新数据库?如何更改表的列数据? 4.如何获取数据库? 5.如何修改数 ...
- opencv png和jpg的叠加
char *bgFile = "C:/C_Project/HandTraining/Debug/res/bg.jpg"; FILE *file = fopen(bgFile, &q ...
- python 字节与字符串转换
name = 'laogaoyang' nameBytes = name.encode('utf-8') # 字节 nameStr = nameBytes.decode('utf-8')# 字符串 p ...
- PHP微信支付开发实例
这篇文章主要为大家详细介绍了PHP微信支付开发过程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 PHP微信支付开发过程,分享给大家,供大家参考,具体内容如下 1.开发环境 Thinkphp 3. ...
- Delphi中Interface接口的使用方法
示例注释(现在应该知道的): { 1.接口命名约定 I 起头, 就像类从 T 打头一样. 2.接口都是从 IInterface 继承而来; 若是从根接口继承, 可省略. 3.接口成员只能是 ...