LeetCode 425. Word Squares 单词平方

来源:互联网 发布:学淘宝美工要准备什么 编辑:程序博客网 时间:2024/06/06 00:39

[LeetCode] 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:

There are at least 1 and at most 1000 words.
All words will have the exact same length.
Word length is at least 1 and at most 5.
Each word contains only lowercase English alphabeta-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 matters).

思路:
*1.自己想的方法是,DFS+pruning,对[“area”,”lead”,”wall”,”lady”,”ball”],让第一行为area,然后第二行为lead,看这两行的前两列是否构成单词平方,不是则break让第二行为wall,是则继续看第三行。这个思路的特点是,对所有可能的组合去一一判断是否是word squares。

*2.这个思路的相对的思路是,按照word squares一步一步的构造,例如:第一行先选wall, 则第二行开头必须是a才能构成word squares,所以只需要尝试以a开头的单词,发现area可以做第二行,然后第三行开头必须是le才能构成word squares,所以只需要尝试以le做前缀的词,发现lead满足条件,然后第四行必须是以lad开头的,所以找到lady,这时可以把找到的word square存起来,再尝试新的。

class Solution {public:    vector<vector<string>> wordSquares(vector<string>& words){    //用hashtable存每个单词所有前缀    //参考代码:https://discuss.leetcode.com/topic/63387/java-ac-solution-easy-to-understand    n=words[0].size();    for(auto&word:words){        for(int i=0;i<n;i++){            mm[word.substr(0,i)].push_back(word);        }    }    helper(0);    return squares;    }    int n;    unordered_map<string,vector<string>> mm;    vector<string> square(n,string<n,"">);    vector<vector<string>> squares;    void helper(int i){        if(i==n){squares.push_back(square);return;}        string prefix;        for(int k=0;k<i;k++)            prefix+=square[i][k];        for(string&word:mm[prefix]){            square[i]=word;            helper(i+1);        }    }    //当用iterative比较复杂,代码量太大,则用recursive来写。    /*for(int i=0;i<words.size();i+=){        square[0]=words[i];        for(int j=0;j<n;j++){            for(int k=0;k<j;k++){        }        }    }*/    }    };
0 0
原创粉丝点击