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();
            }
        }
    }
};
原文地址:https://www.cnblogs.com/casperwin/p/13676979.html