leetcode 單詞拆分II

2021-09-25 04:22:20 字數 3002 閱讀 1342

這道題一眼看去,就死類似於單詞拆分i的深度優先搜尋就可以解決的題目,不過這裡公升級了,就是要把每一種切分結果都要返回。

具體**如下:

class

solution

:def

wordbreak

(self, s:

str, worddict: list[

str])-

> list[

str]

: mem =

tmp = self.dfs(s, worddict, mem)

res =

for item in tmp:

' '.join(item)

)return res

defdfs(self, s, worddict, mem)

:if self.check(s, worddict)

==false

:return

if s in mem.keys():

return mem[s]

if s =='':

return[[

]]res =

for i in

range(1

,len

(s)+1)

:if s[

:i]in worddict and self.check(s[i:

], worddict)

: substr = self.dfs(s[i:

], worddict, mem)

for item in substr:

[s[:i]

]+ item)

return res

defcheck

(self, s, worddict)

:if s in worddict:

return

true

index_set =

[false]*

(len

(s)+1)

index_set[0]

=true

for i in

range(1

,len

(s)+1)

:# i [1, 8]

for idx in

range

(i):

# idx [0, 7]

if index_set[i]

==false

and index_set[idx]

and s[idx:i]

in worddict:

index_set[i]

=true

return index_set[-1

]

1.反向判斷,判斷每乙個字元的位置到最終的位置之間的子串是否可分,判斷完之後將這個bool陣列儲存起來;

2.正向dfs,利用反向判斷的資訊可以快速判斷後面是否可以分解,從而避免不必要的計算量;

具體**如下:

class

solution

:'''反向判斷'''

defwordbreak

(self, s:

str, worddict: list[

str])-

> list[

str]

: judges = self.get_judgement(s, worddict)

if judges[0]

==false

:return

mem =

res =

tmp = self.dfs(s, worddict, mem, judges)

for item in tmp:

' '.join(item)

)return res

defdfs(self, s, worddict, mem, judges)

:if s in mem.keys():

return mem[s]

if s =='':

return[[

]]res =

for i in

range(1

,len

(s)+1)

:#先判斷字典中是不是存在這個字串,然後判斷這個字串後面是否能分解

if s[

:i]in worddict and judges[i]

: substr = self.dfs(s[i:

], worddict, mem, judges[i:])

for item in substr:

[s[:i]

]+ item)

mem[s]

= res

return res

defget_judgement

(self, s, worddict)

:#len(s) = 5

res =

[false]*

(len

(s)+1)

res =

[false]*

(len

(s)+

1)

res[-1

]=true

for i in

range

(len

(s))[:

:-1]

:#i 7 to 0

for ptr in

range

(i+1

,len

(s)+1)

[::-

1]:#ptr 8 to i+1

if res[i]

==false

and res[ptr]

and s[i:ptr]

in worddict:

res[i]

=true

return res

經過改進之後,時間複雜度得到了很大的提公升,可以提交觀察結果檢視。

LeetCode140 單詞拆分II

leetcode140.單詞拆分ii 動態規劃 dfs 回溯。動態規劃 根據139單詞拆分使用動態規劃dp j i 表示從s j.i 1 是可拆分的,可以理解為長度len的字串有len 1可以分割的位置。dfs 遞迴的遍歷當前字串,vectorpath用來記錄能夠拆分的一條路徑。回溯 同一分支的多種...

LeetCode 140 單詞拆分 II

問題描述 給定乙個非空字串 s 和乙個包含非空單詞列表的字典 worddict,在字串中增加空格來構建乙個句子,使得句子中所有的單詞都在詞典中。返回所有這些可能的句子。說明 示例 1 輸入 s catsanddog worddict cat cats and sand dog 輸出 cats and...

leetcode140 單詞拆分 II

給定乙個非空字串 s 和乙個包含非空單詞列表的字典 worddict,在字串中增加空格來構建乙個句子,使得句子中所有的單詞都在詞典中。返回所有這些可能的句子。先判斷能否拆分,再dfs得出結果 class solution def wordbreak self,s str,worddict list ...