zoukankan      html  css  js  c++  java
  • 30 Day Challenge Day 9 | Leetcode 425. Word Squares

    题解

    一道 hard 级别题。

    递归 + 暴力查找前缀,超时了。

    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;
            
            for(int i = 0; i < num; i++) {
                vector<string> result;
                result.push_back(words[i]);
                search(words, size, result, results);
            }
            
            return results;
        }
        
        void search(vector<string>& words, int size, vector<string>& result, vector<vector<string>>& results) {
            if(result.size() == size) {
                results.push_back(result);
                return;
            }
            
            string next_word;
            for(int i = 0; i < result.size(); i++) {
                next_word += result[i][result.size()];
            }
            
            for(auto word : words) {
                if(word.substr(0, next_word.size()) == next_word) {
                    result.push_back(word);
                    search(words, size, result, results);
                    result.pop_back();
                }
            }
        }
    };
    
  • 相关阅读:
    spider
    python 2.X
    django 创建项目
    NameError: name 'pip' is not defined
    异常捕获
    @property
    node-Telnet
    ES6-模块化
    高级排序算法之双路快速排序
    高级排序算法之快速排序
  • 原文地址:https://www.cnblogs.com/casperwin/p/13676979.html
Copyright © 2011-2022 走看看