LeetCode_Word Break II
一、題目描述:
二、解決思路:
題目要求我們要在原字符串中加空格,使得隔開的每個詞都是詞典中的詞。
所以我們大可以按順序掃描每個字符,但是然後當碰到是詞典中的詞,就加個空格,但是要求返回的結果按題目的提醒是個List,說明有很多分隔方式。
再細細想問題,我們發現第二個詞能被成功分隔出來,是因爲第一個詞已經分出來了,依次類推;所以我們可以採用動態規劃,設置初值dp[0] 是一個 List;遞推式是 dp[n] = dp[n-1] && a[n] (a[n] = dict.contains(每次截斷的字符串))。
這樣,我們通過動態規劃,就獲得了字符串中每個字符索引處的單詞。dp[10] = {“dog”}, dp[7]={“and”,”sand”}, dp[4]={“cats”}, dp[3]={“cat”}, dp[0]={},其他都是null。
最後我們要做的就是按順序組合字符串,放到List中,返回。怎麼組合呢?這就可以利用dfs遞歸。在我理解,可以把遞歸想象成一個棧,重要的是設置結束條件和在剔除棧頂元素。
三、Java代碼:
public class Solution {
public List<String> wordBreak(String s, Set<String> wordDict) {
List<String>[] dp = new ArrayList[s.length()+1];
dp[0] = new ArrayList<String>();//設置初值
for(int end=1; end<=s.length(); end++) {//substring的endIndex
for(int start=end-1; start>=0; start--) {
String word = s.substring(start,end);
if(dp[start] != null && wordDict.contains(word)) { //動態規劃遞推式
if(dp[end] == null) {
dp[end] = new ArrayList<String>();
}
dp[end].add(word);
}
}
}
List<String> result = new ArrayList<String>();
if(dp[s.length()] == null)
return result;
else {
List<String> temp = new ArrayList<String>();
dsfStringList(dp,s.length(),result,temp);
return result;
}
}
private static void dsfStringList(List<String>[] dp, int end, List<String> res, List<String> temp) {
if(end <= 0) { //遞歸結束條件
String s = temp.get(temp.size()-1);
for(int i = temp.size()-2; i >= 0; i--)
s += (" "+temp.get(i));
res.add(s);
return;
}
for(String str : dp[end]) {
temp.add(str);
dsfStringList(dp, end-str.length(), res, temp); //遞歸式
temp.remove(temp.size()-1);
}
}
}
希望與大家多多交流!