Leetcode 425

Leetcode 425 Word Square

题意:找所有满足要求的能够成对称矩阵的字符串的合集
代码:https://leetcode.com/problems/word-squares/description/

    class Solution{
    public:
        struct TrieNode{
            vector<int> indexes;
            vector<TrieNode*> children;
            TrieNode():children(26,NULL){}
        };

        TrieNode* buildTree(vector<string>& words){
            TrieNode* root = new TrieNode();
            for(int i=0;i<words.size();i++){
                TrieNode* cur = root;
                for(int j=0;j<words[i].size();j++){
                    if(cur->children[words[i][j]-'a']==NULL)
                        cur->children[words[i][j]-'a'] = new TrieNode();
                    cur = cur->children[words[i][j]-'a'];
                    cur->indexes.push_back(i);
                }
            }
            return root;
        }

        vector<vector<string>> wordSquares(vector<string> words){
            TrieNode* root = buildTree(words);
            vector<string> out(words[0].size()):
            for(int i=0;i<words.size();i++){
                out[0] = words[i];
                helper(words, root, 1, out, res);
            }
            return res;
        }

        void helper(vector<string>& words, TreeNode* root, int level, vector<string>& out, vector<vector<string>>& res){
            if(level>=out.size()){
                res.push_back(out);
                return;
            }
            string str = "";
            for(int i=0;i<level; i++){
                str+=out[i][level];
            }
            TreeNode* cur = root;
            for(int i=0;i<level; i++){
                if(cur->children[str[i]-'a'] == NULL) cur=cur->children[str[i]-'a];
                cur = cur->children[str[i]-'a'];
            }

            for(int idx:cur->indexes){
                out[level] = words[idx];
                helper(words, root, level+1, out, res);
            }

        }


    }
全部评论

相关推荐

11-26 22:34
已编辑
重庆邮电大学 Java
快手 客户端开发 (n+5)k*16 公积金12
牛客895077908号:佬 什么双非硕啊
点赞 评论 收藏
分享
ArisRobert:统一解释一下,第4点的意思是,公司按需通知员工,没被通知到的员工是没法去上班的,所以只要没被通知到,就自动离职。就是一种比较抽象的裁员。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务