給定一個非空字符串 s 和一個包含非空單詞列表的字典 wordDict,在字符串中增長空格來構建一個句子,使得句子中全部的單詞都在詞典中。返回全部這些可能的句子。算法
說明: 分隔時能夠重複使用字典中的單詞。 你能夠假設字典中沒有重複的單詞。app
示例 1:ui
輸入:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
輸出:
[
"cats and dog",
"cat sand dog"
]
複製代碼
示例 2:spa
輸入:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
輸出:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
解釋: 注意你能夠重複使用字典中的單詞。
複製代碼
示例 3:code
輸入:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
輸出:
[]
複製代碼
這道題是上一題的升級版,既然須要返回全部結果,那麼回溯基本上跑不了了。不過這道題不能強行回溯,會超時的,須要用到上一題的動態規劃先判斷字符串能不能被拆分,若是能夠再進行回溯。 碼到成功:cdn
func wordBreak(s string, wordDict []string) []string {
wMap := make(map[string]bool,len(wordDict))
for _,v := range wordDict {
wMap[v] = true
}
//先經過DP判斷字符串是否能被拆分
dp := make([]bool, len(s)+1)
dp[0] = true
for i:=1;i<=len(s);i++ {
for j:=0;j<i;j++ {
if dp[j] && wMap[s[j:i]] {
dp[i] = true
break
}
}
}
re := []string{}
if !dp[len(s)] {
return re
}
//回溯走起
var DFS = func (string,[]string) {}
DFS = func(ns string,r []string) {
if len(ns) == 0 {
re = append(re, strings.Join(r," "))
return
}
for i:=1; i<=len(ns); i++ {
if wMap[ns[:i]] {
DFS(ns[i:],append(r,ns[:i]))
}
}
}
DFS(s,[]string{})
return re
}
複製代碼
話很少說,繼續努力!圖片
算法夢想家,來跟我一塊兒玩算法,玩音樂,聊聊文學創做,我們一塊兒天馬行空! leetcode