生活随笔
收集整理的這篇文章主要介紹了
LeetCode 140. 单词拆分 II(DP+回溯)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 題目
給定一個非空字符串 s 和一個包含非空單詞列表的字典 wordDict,在字符串中增加空格來構建一個句子,使得句子中所有的單詞都在詞典中。返回所有這些可能的句子。
說明:
分隔時可以重復使用字典中的單詞。
你可以假設字典中沒有重復的單詞。
示例
1:
輸入
:
s
= "catsanddog"
wordDict
= ["cat", "cats", "and", "sand", "dog"]
輸出
:
["cats and dog","cat sand dog"
]示例
2:
輸入
:
s
= "pineapplepenapple"
wordDict
= ["apple", "pen", "applepen", "pine", "pineapple"]
輸出
:
["pine apple pen apple","pineapple pen apple","pine applepen apple"
]
解釋
: 注意你可以重復使用字典中的單詞。示例
3:
輸入
:
s
= "catsandog"
wordDict
= ["cats", "dog", "sand", "and", "cat"]
輸出
:
[]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/word-break-ii
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. DP+回溯
相關題目:LeetCode 139. 單詞拆分(DP)
- 先在139題的基礎上,判斷單詞是否可以拆分
- 如果可以的話,進行回溯,暴力查找所有可能
class Solution {
public:vector
<string
> wordBreak(string s
, vector
<string
>& wordDict
) {int i
, j
, n
= s
.size();unordered_set
<string
> set(wordDict
.begin(), wordDict
.end());bool dp
[n
+1] = {false};dp
[0] = true;for(i
= 0; i
<= n
; ++i
){if(dp
[i
] == true)for(j
= i
+1; j
<= n
; ++j
){if(set
.count(s
.substr(i
,j
-i
)))dp
[j
] = true;}}if(dp
[n
] == true){vector
<string
> ans
;string str
;int end
= 1;while(end
<= n
&& dp
[end
] != 1)end
++;bt(s
,set
,dp
,ans
,str
,0,end
);return ans
;}elsereturn {};}void bt(string
&s
, unordered_set
<string
> &set
, bool *dp
, vector
<string
> &ans
,string str
, int start
, int end
){if(start
>= end
)return;string temp
= s
.substr(start
,end
-start
);bool inSet
= set
.count(temp
);if(end
== s
.size()){if(inSet
)ans
.push_back(str
+temp
);return;}int next
= end
+1;while(next
<= s
.size() && dp
[next
] != 1)next
++;bt(s
,set
,dp
,ans
,str
,start
,next
);if(inSet
)bt(s
,set
,dp
,ans
,str
+temp
+" ",end
,next
);}
};
總結
以上是生活随笔為你收集整理的LeetCode 140. 单词拆分 II(DP+回溯)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。