一、dfs+字典樹+回溯給定乙份單詞的清單,設計乙個演算法,建立由字母組成的面積最大的矩形,其中每一行組成乙個單詞(自左向右),每一列也組成乙個單詞(自上而下)。不要求這些單詞在清單裡連續出現,但要求所有行等長,所有列等高。
如果有多個面積最大的矩形,輸出任意乙個均可。乙個單詞可以重複使用。
示例 1:
輸入: ["this", "real", "hard", "trh", "hea", "iar", "sld"]
輸出:[
"this",
"real",
"hard"
]示例 2:
輸入: ["aa"]
輸出: ["aa","aa"]
說明:words.length <= 1000
words[i].length <= 100
資料保證單詞足夠隨機
#構建trie樹
class trie(object):
def __init__(self):
self.root = [{}, false]
def add_word(self, word):
cur = self.root
for c in word:
if c not in cur[0]:
cur[0][c] = [{}, false]
cur = cur[0][c]
cur[1] = true
class solution:
def maxrectangle(self, words: list[str]) -> list[str]:
def dfs(arr, li):
for word in words:
#找到和單詞長度一樣的
if len(word) != len(arr):
continue
for i, w in enumerate(word):
if w not in arr[i][0]:
break
else:
temp = arr[:]
flag = true
for i, w in enumerate(word):
temp[i] = temp[i][0][w]
flag &= temp[i][1]
if flag:
len_li, len_word = len(li), len(word)
nonlocal area, res
if len_li * len_word > area:
area = len_li * len_word
res = li[:]
dfs(temp, li)
li.pop()
#構建字典樹
area = 0
res =
trie = trie()
for word in words:
trie.add_word(word)
#將單詞的長度遞減排序
len_words = sorted(set(len(word) for word in words), reverse = true)
for len_word in len_words:
if len_word * len_words[0] < area:
break
dfs([trie.root]*len_word, )
return res
單詞矩陣 貳五語言
problemcodevs 洛谷 題意 對於包含字母a到y各一次的單詞s,將其從上到下從左到右寫在乙個5 5的矩陣中,如單 詞adjptbekqucglrvfinswhmoxy寫出來如下 a d j p t b e k q u c g l r v f i n s w h m o x y 若該矩陣滿足...
codevs1322 單詞矩陣
題目描述 description 對於包含字母a到y各一次的單詞s,將其從上到下從左到右寫在乙個5 5的矩陣中,如單 詞adjptbekqucglrvfinswhmoxy寫出來如下 a d j p t b e k q u c g l r v f i n s w h m o x y 若該矩陣滿足每一行...
Codevs1322 單詞矩陣
對於包含字母a到y各一次的單詞s,將其從上到下從左到右寫在乙個5 5的矩陣中,如單詞adjptbekqucglrvfinswhmoxy寫出來如下 a d j p t b e k q u c g l r v f i n s w h m o x y 若該矩陣滿足每一行每一列的字母都是字典序遞增的則稱s為...