leetcode 140. 单词拆分 II

题解

记忆化回溯,hash[s] 保存相应字符串 s 对应的单词组合

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
func wordBreak(s string, wordDict []string) []string {
hash := make(map[string][]string)
wordHash := make(map[string]bool)
for _, word := range wordDict {
wordHash[word] = true
}
return dfs(s, wordDict, hash, wordHash)
}

func dfs(s string, wordDict []string, hash map[string][]string, wordHash map[string]bool) []string {
if _, ok := hash[s]; ok {
return hash[s]
}
res := make([]string, 0)
n := len(s)
if n == 0 {
res = append(res, "")
return res
}
for i := 0; i < n; i++ {
if wordHash[s[:i+1]] {
sublist := dfs(s[i+1:], wordDict, hash, wordHash)
for _, sub := range sublist {
space := " "
if sub == "" {
space = ""
}
res = append(res, s[:i+1]+space+sub)
}
}
}
hash[s] = res
return res
}