1
+ // 简单的回溯 29 / 36 test cases passed. 超时了
2
+ class Solution
3
+ {
4
+ public:
5
+ bool wordBreak (string s, vector<string>& wordDict)
6
+ {
7
+ if (s.length () == 0 )
8
+ return true ;
9
+
10
+ for (int i = 0 ; i < s.length (); i++)
11
+ {
12
+ if (inWordDict (s.substr (0 , i + 1 ), wordDict) && wordBreak (s.substr (i + 1 ), wordDict))
13
+ return true ;
14
+ }
15
+ return false ;
16
+ }
17
+ private:
18
+ bool inWordDict (string &s, vector<string> &wordDict)
19
+ {
20
+ for (auto str: wordDict)
21
+ {
22
+ if (s == str)
23
+ return true ;
24
+ }
25
+ return false ;
26
+ }
27
+ };
28
+
29
+ // 思路二 同样使用回溯,区别在于对于思路一的代码进行加速
30
+ // 29 / 36 test cases passed. 同样超时了
31
+ class Solution
32
+ {
33
+ public:
34
+ bool wordBreak (string s, vector<string>& wordDict)
35
+ {
36
+ if (s.length () == 0 )
37
+ return true ;
38
+
39
+ for (auto word : wordDict)
40
+ {
41
+ if (s.substr (0 , word.length ()) == word)
42
+ {
43
+ if (wordBreak (s.substr (word.length ()), wordDict))
44
+ return true ;
45
+ }
46
+ }
47
+ return false ;
48
+ }
49
+ };
50
+
51
+
52
+ // 思路三 区别与思路二就是加入了备忘录
53
+ // Runtime: 8 ms, faster than 99.55% of C++ online submissions for Word Break.
54
+ // Memory Usage: 9.9 MB, less than 87.92% of C++ online submissions for Word Break.
55
+
56
+ class Solution
57
+ {
58
+ public:
59
+ bool wordBreak (string s, vector<string>& wordDict)
60
+ {
61
+ bool *visited = new bool [s.length () + 1 ]();
62
+
63
+ bool res = helper (s, wordDict, visited);
64
+
65
+ delete[] visited;
66
+
67
+ return res;
68
+ }
69
+ private:
70
+ bool helper (string s, vector<string>& wordDict, bool * visited)
71
+ {
72
+ if (visited[s.length ()])
73
+ return false ;
74
+ else
75
+ {
76
+ if (s.length () == 0 )
77
+ return true ;
78
+
79
+ for (auto word : wordDict)
80
+ {
81
+ if (s.substr (0 , word.length ()) == word)
82
+ {
83
+ if (helper (s.substr (word.length ()), wordDict, visited))
84
+ return true ;
85
+ }
86
+ }
87
+ visited[s.length ()] = true ;
88
+ return false ;
89
+ }
90
+ }
91
+ };
0 commit comments