zoukankan      html  css  js  c++  java
  • 30 Day Challenge Day 16 | Leetcode 701. Insert into a Binary Search Tree

    题解

    Hard

    方法:Trie

    struct TrieNode {
        vector<int> indexes;
        vector<TrieNode*> next;
        
        TrieNode() : next(26, nullptr) {
            
        }
    };
    
    class Solution {
    public:
        vector<vector<string>> wordSquares(vector<string>& words) {
            // the size of a word determine the square size
            int num = words.size(), size = words[0].size();
    
            vector<vector<string>> results;
            vector<string> result;
            
            TrieNode* root = buildTrieTree(words);
            
            for(auto word : words) {
                result.push_back(word);
                search(words, size, root, result, results);
                result.pop_back();
            }
            
            return results;
        }
        
        TrieNode* buildTrieTree(vector<string>& words) {
            TrieNode* root = new TrieNode();
    
            for(int i = 0; i < words.size(); i++) {
                TrieNode* node = root;
                for(auto c : words[i]) {
                    if(!(node->next[c-'a'])) node->next[c-'a'] = new TrieNode();
                    node = node->next[c-'a'];
                    node->indexes.push_back(i);
                }
            }
            
            return root;
        }
        
        void search(vector<string>& words, int size, TrieNode* root, vector<string> result, vector<vector<string>>& results) {
            if(result.size() == size) {
                results.push_back(result);
                return;
            }
            
            string prefix;
            for(int i = 0; i < result.size(); i++) {
                prefix += result[i][result.size()];
            }
            
            TrieNode* node = root;
            for(auto c : prefix) {
                if(!(node->next[c-'a'])) return;
                node = node->next[c-'a'];
            }
            
            for(int i : node->indexes) {
                result.push_back(words[i]);
                search(words, size, root, result, results);
                result.pop_back();
            }
        }
    };
    
  • 相关阅读:
    ffmpeg基本用法
    MySQL中使用like查找汉字 Incorrect string value 解决办法
    mysql存储过程变量的拼接
    解决IIS8中 URLRewriter 不能使用的方法
    Unix系统介绍
    远程控制客户端界面介绍
    远程控制之登录界面设计
    搞了一周,终于把视频流在局域网内传输搞定
    servelet
    前后台贯穿
  • 原文地址:https://www.cnblogs.com/casperwin/p/13757232.html
Copyright © 2011-2022 走看看