[Leetcode] 425. Word Squares 解题报告

题目

Given a set of words (without duplicates), find all word squares you can build from them.

A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).

For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically.

b a l l
a r e a
l e a d
l a d y

Note:

  1. There are at least 1 and at most 1000 words.
  2. All words will have the exact same length.
  3. Word length is at least 1 and at most 5.
  4. Each word contains only lowercase English alphabet a-z.

Example 1:

Input:
["area","lead","wall","lady","ball"]

Output:
[
  [ "wall",
    "area",
    "lead",
    "lady"
  ],
  [ "ball",
    "area",
    "lead",
    "lady"
  ]
]

Explanation:
The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters).

Example 2:

Input:
["abat","baba","atan","atal"]

Output:
[
  [ "baba",
    "abat",
    "baba",
    "atan"
  ],
  [ "baba",
    "abat",
    "baba",
    "atal"
  ]
]

Explanation:
The output consists of two word squares. The order of output does not matter (just the order of words in each word square matt

思路

还是那句老话:对于需要求出所有可行解的问题来讲,BackTracking都是不二选择(至少从我目前遇到的Leetcode题目来讲都是如此)。对于本题而言,我们同样可以采用BackTracking,逐个试着加每个word,一旦发现solution的size已经和word的length一样了,并且还没有违反Word Square的规则,那么该solution就是一个可行解,把它加入解集就可以了。当采用深度优先搜索(dfs)获得所有可行的solution之后,返回即可。

当然作为难度为hard的Leetcode题目而言,不可能这么简单的让你通过测试。由于涉及大量的搜索words中的单词,以及判断某个单词加入之后是否仍然符合word square的规则,所以采用暴力搜索肯定会超时。幸亏我们在前面的题目中多次采用过Trie这种数据结构,来加速对包含通配符在内的单词的搜索,这里刚好就派上用场了!怎么做呢?1)把words里面的所有单词加入Trie中,建立一个字典树。2)采用BackTracking的策略来求得符合条件的所有解(这个过程里面还有一些技巧,请看下面代码片段的注释)。

代码

class TrieNode
{
public:
    bool isComplete;
    TrieNode* ch[26];
    TrieNode() {
        isComplete = false;
        for(int i = 0; i < 26; ++i) {
            ch[i] = NULL;
        }
    }
};

class Trie
{
public:
    Trie() {
        root = new TrieNode();
    }
    
    void insert(string word) {
        TrieNode* p = root;
        for(auto c : word) {
            if(p->ch[c - 'a'] == NULL)
                p->ch[c - 'a'] = new TrieNode();
            p = p->ch[c - 'a'];
        }
        p->isComplete = true;
    }
    
    void search(TrieNode* p, string& word, int startIndex, string line, vector<string> &ret) {
        if(p == NULL)
            return;
        if(startIndex == word.length()) {
            if(p->isComplete) {
                ret.push_back(line);
            }
            return;
        }
        char c = word[startIndex];
        if(c != '.') {
            search(p->ch[c-'a'], word, startIndex + 1, line + c, ret);
        }
        else {
            for(int i = 0; i < 26; ++i) {
                if(p->ch[i] != NULL) {
                    char temp_c = 'a' + i;
                    search(p->ch[i], word, startIndex + 1, line + temp_c, ret);
                }
            }
        }
    }
    
    TrieNode* getRoot() {
        return root;
    }
private:
    TrieNode* root;
};

class Solution {
public:
    vector<vector<string>> wordSquares(vector<string>& words) {
        vector<vector<string>> ret;
        if(words.size() == 0 || words[0].length() == 0) {
            return ret;
        }
        int word_length = words[0].length();
        Trie trie;                                  // build the Trie
        for(int i = 0; i < words.size(); ++i) {
            trie.insert(words[i]);
        }
        vector<string> solution;
        for(int i = 0; i < words.size(); ++i) {     // try to put word[i] to the solution
            solution.push_back(words[i]);
            dfs(trie, word_length, ret, solution);
            solution.pop_back();    // backtracking
        }
        return ret;
    }
private:
    void dfs(Trie& trie, int word_length, vector<vector<string>> &ret, vector<string> &solution) {
        if(solution.size() == word_length) {
            ret.push_back(solution);
            return;
        }
        int size = solution.size();
        string word;                                            // Find how the word should be. '.' means any letter can be here
        for(int i = 0; i < word_length; ++i) {
            if(i < size) {
                word += solution[i][size];
            }
            else {
                word += '.';
            }
        }
        vector<string> candidates;                              // Collect the possible words that fullfill the structure of word
        trie.search(trie.getRoot(), word, 0, "", candidates);
        for(int i = 0; i < candidates.size(); ++i) {            // Backtracking to find all the possible solutions
            solution.push_back(candidates[i]);
            dfs(trie, word_length, ret, solution);
            solution.pop_back();
        }
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值