问题描述
我的解决方案是正确的并且通过了所有测试用例,但是我的解决方案非常慢(比 C++ 解决方案的 7% 快)。
问题: 给定一个 m x n 字符板和一个字符串单词列表,返回板上的所有单词。 每个单词必须由顺序相邻单元格的字母构成,其中相邻单元格水平或垂直相邻。同一个字母单元格不能在一个单词中多次使用。
例如:
输入:board = [["o","a","n"],["e","t","e"],["i ","h","k","r"],["i","f","l","v"]],words = ["oath","pea","eat","雨”] 输出:["eat","oath"]
顺便说一下,我没有 Leetcode premium 并查看了讨论。我看到其他人正在使用递归。我正在使用堆栈,但这应该不是问题。有没有人看到我的代码有任何性能问题?复杂度应该是 O(n^2*3^n)
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board,vector<string>& words) {
vector<string> ret;
Trie* root = new Trie();
for (const auto &i:words) {
root->insert(i);
}
Trie* cnode = root;
int numRow = board.size();
int numCol = board[0].size();
vector<int> temp(numCol,0);
vector<vector<int>> visited(numRow,temp);
for (int i = 0; i < numRow; ++i) {
for (int j = 0; j < numCol; ++j) {
stack<pair<int,int>> searcher;
searcher.push(make_pair(i,j));
while (!searcher.empty()) {
int row = searcher.top().first;
int col = searcher.top().second;
int cur = board[row][col] - 97;
if (visited[row][col]) {
cnode = cnode->parent;
visited[row][col] = 0;
searcher.pop();
} else if (cnode->child[cur] == nullptr) {
searcher.pop();
visited[row][col] = 0;
} else {
visited[row][col] = 1;
cnode = cnode->child[cur];
if (cnode->contain != "") {
ret.push_back(cnode->contain);
cnode->contain = "";
}
if (row + 1 < numRow && !visited[row + 1][col]) {
searcher.push(make_pair(row+1,col));
}
if (row - 1 >= 0 && !visited[row-1][col]) {
searcher.push(make_pair(row-1,col));
}
if (col + 1 < numCol && !visited[row][col+1]) {
searcher.push(make_pair(row,col+1));
}
if (col - 1 >= 0 && !visited[row][col-1]) {
searcher.push(make_pair(row,col-1));
}
}
}
}
}
return ret;
}
class Trie {
public:
vector<Trie*> child;
Trie* parent;
string contain;
Trie() {
child = vector<Trie*>(26,nullptr);
contain = "";
parent = nullptr;
}
void insert(string word) {
Trie* root = this;
for (int i = 0; i < word.size(); ++i) {
int loc = word[i] - 97;
if (root->child[loc] == nullptr) {
root->child[loc] = new Trie();
root->child[loc]->parent = root;
}
root = root->child[loc];
}
root->contain = word;
}
};
};
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)