###### LeetCode 425. Word Squares 单词平方

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

Output:

] ]

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).

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++){
}
}
}*/
}
};

#### [Leetcode] 425. Word Squares 解题报告

2017-11-06 15:25:42

#### Squares

2015-11-25 21:37:50

#### E - Squares

2018-02-24 15:57:46

#### Algorithms: Squares Related Questions

2017-03-21 08:48:42

#### 318. Maximum Product of Word Lengths

2017-02-17 10:34:09

#### 283. Move Zeroes

2017-02-14 10:18:57

#### LeetCode: Valid Word Square

2016-10-16 11:29:35

#### Squares(POJ--2002

2015-08-12 09:37:21

#### leetcode 279. Perfect Squares-完美平方数|动态规划

2016-06-04 17:14:59

#### LeetCode--279. Perfect Squares（完美平方）Python

2018-01-02 17:01:12

## 不良信息举报

LeetCode 425. Word Squares 单词平方