LeetCode刷题实战425:单词方块
示例
示例 1:
输入:
["area","lead","wall","lady","ball"]
输出:
[
[ "wall",
"area",
"lead",
"lady"
],
[ "ball",
"area",
"lead",
"lady"
]
]
解释:
输出包含两个单词方块,输出的顺序不重要,只需要保证每个单词方块内的单词顺序正确即可。
示例 2:
输入:
["abat","baba","atan","atal"]
输出:
[
[ "baba",
"abat",
"baba",
"atan"
],
[ "baba",
"abat",
"baba",
"atal"
]
]
解释:
输出包含两个单词方块,输出的顺序不重要,只需要保证每个单词方块内的单词顺序正确即可。
解题
class Solution {
public:
int limit;
unordered_map<string,unordered_set<int>> mp;
vector<vector<string>> wordSquares(vector<string>& words) {
if(words.empty() or words[0].empty()){return {};}
vector<vector<string>> res;
limit=words[0].size();
vector<int> cur;
for(int i=0;istring prefix="";
for(int j=0;jprefix+=words[i][j];
mp[prefix].insert(i);
}
}
for(int i=0;icur.emplace_back(i);
dfs(res,words,cur);
cur.pop_back();
}
return res;
}
void dfs(vector<vector<string>>& res,vector<string>& words,vector<int>& cur){
// for(int x:cur){
// cout<
// }cout<<"-----------------"<
if(cur.size()>=limit){//加入结果数组
vector<string> cur_res;
for(int i=0;icur_res.emplace_back(words[cur[i]]);
}
res.emplace_back(move(cur_res));
return;
}
string prefix="";//先算下一个单词需要满足的前缀
for(int j=0;jprefix+=words[cur[j]][cur.size()];
}
if(mp.count(prefix)){
for(int i:mp[prefix]){
cur.push_back(i);
dfs(res,words,cur);
cur.pop_back();
}
}
}
};