leetcode 425+lintcode 634-- TrieNode

这个题用典型的前缀树解决:


图片.png

整个代码递归过程:


图片.png
//my
class Solution {
public:
    struct TrieNode {
        vector<TrieNode*> child = vector<TrieNode*>(26, nullptr);
        vector<int> idx;
    };
    TrieNode* insert(TrieNode* root, vector<string>& words) {
        
        for (int i = 0; i < words.size(); i++) {
            TrieNode* temp = root;
            for (int j = 0; j < words[i].size(); j++) {
                if (temp->child[words[i][j] - 'a'] == nullptr)
                    temp->child[words[i][j] - 'a'] = new TrieNode();
                temp->idx.push_back(i);
                temp = temp->child[words[i][j] - 'a'];
            }
        }
        return root;
    }
    void helper(TrieNode *root, int level, vector<vector<string>>& ans, vector<string>& out, vector<string>& words) {
        if (level >= out[0].size()) {
            ans.push_back(out);
            return;
        }
        string str = "";
        for (int i = 0; i < level; i++)
            str += out[i][level];
        TrieNode* temp = root;
        for (auto cc : str) {
            if (temp->child[cc - 'a'] == nullptr)
                return;
            temp = temp->child[cc - 'a'];
        }//out of loop we point to the next node
        for (auto aa : temp->idx) {
            out[level]=(words[aa]);
            helper(root, level + 1, ans, out, words);
        }
    }
    vector<vector<string>> wordSquares(vector<string>& words) {
        TrieNode * root=new TrieNode();
        root=insert(root,words);
        vector<vector<string>> ans;
        vector<string> out(words[0].size());// not exact number
        for (auto aa : words) {
            out[0]=aa;
            helper(root, 1, ans, out,words);
        }
        return ans;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • LeetCode 刷题随手记 - 第一部分 前 256 题(非会员),仅算法题,的吐槽 https://leetc...
    蕾娜漢默阅读 18,087评论 2 36
  • 动态规划 111. 爬楼梯思路类似斐波那契数列注意考虑第 0 阶的特殊情况 272. 爬楼梯 II思路类似上题,只...
    6默默Welsh阅读 7,116评论 0 1
  • 链接地址:https://www.tutorialspoint.com/compiler_design/compi...
    dannyvi阅读 10,211评论 1 12
  • 我有一辆电动车,骑了好几年了,因为不大爱惜导致车没反光镜,没刹车,没喇叭。有一次同事有急事借骑一下,第二天全公司的...
    读物杂志阅读 812评论 0 0
  • 相信每个人身边都有都有很多不同性格的朋友,比如那些脾气暴躁,动不动就容易生气的人,很容易会让人想要远离他们,那么现...
    星座天使阅读 4,799评论 2 2