mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
@ -89,27 +89,26 @@ class Solution {
|
|||||||
private:
|
private:
|
||||||
bool backtracking (const string& s,
|
bool backtracking (const string& s,
|
||||||
const unordered_set<string>& wordSet,
|
const unordered_set<string>& wordSet,
|
||||||
vector<int>& memory,
|
vector<bool>& memory,
|
||||||
int startIndex) {
|
int startIndex) {
|
||||||
if (startIndex >= s.size()) {
|
if (startIndex >= s.size()) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
// 如果memory[startIndex]不是初始值了,直接使用memory[startIndex]的结果
|
// 如果memory[startIndex]不是初始值了,直接使用memory[startIndex]的结果
|
||||||
if (memory[startIndex] != -1) return memory[startIndex];
|
if (!memory[startIndex]) return memory[startIndex];
|
||||||
for (int i = startIndex; i < s.size(); i++) {
|
for (int i = startIndex; i < s.size(); i++) {
|
||||||
string word = s.substr(startIndex, i - startIndex + 1);
|
string word = s.substr(startIndex, i - startIndex + 1);
|
||||||
if (wordSet.find(word) != wordSet.end() && backtracking(s, wordSet, memory, i + 1)) {
|
if (wordSet.find(word) != wordSet.end() && backtracking(s, wordSet, memory, i + 1)) {
|
||||||
memory[startIndex] = 1; // 记录以startIndex开始的子串是可以被拆分的
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
memory[startIndex] = 0; // 记录以startIndex开始的子串是不可以被拆分的
|
memory[startIndex] = false; // 记录以startIndex开始的子串是不可以被拆分的
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
public:
|
public:
|
||||||
bool wordBreak(string s, vector<string>& wordDict) {
|
bool wordBreak(string s, vector<string>& wordDict) {
|
||||||
unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
|
unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
|
||||||
vector<int> memory(s.size(), -1); // -1 表示初始化状态
|
vector<bool> memory(s.size(), 1); // -1 表示初始化状态
|
||||||
return backtracking(s, wordSet, memory, 0);
|
return backtracking(s, wordSet, memory, 0);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
Reference in New Issue
Block a user