-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path140. Word Break II.go
56 lines (44 loc) · 975 Bytes
/
140. Word Break II.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Time C. O(2^n), Space C. O(n)
func wordBreak(s string, wordDict []string)(result []string) {
mapp := make(map[string]int, len(wordDict))
for _, k := range wordDict {
mapp[k] = 0
}
valid := func(word []string) bool {
res := ""
res1 := ""
for i := 0; i < len(word); i++ {
if i != len(word) - 1 {
res += word[i]
res1 += word[i] + " "
}else{
res += word[i]
res1 += word[i]
}
}
if res == s {
result = append(result, res1)
return true
}
return false
}
var backtrack func(currWords []string, st int)
backtrack = func(currWords []string, st int) {
if len(currWords) != 0 && valid(currWords) {
return
}
for i := st; i < len(s); i++ {
res := ""
for j := i; j < len(s); j++ {
res += string(s[j])
if _, ok := mapp[res]; ok {
currWords = append(currWords, res)
backtrack(currWords, j+1)
currWords = currWords[:len(currWords)-1]
}
}
}
}
backtrack([]string{}, 0)
return
}