Update 0139.单词拆分.md

删除原Line 102,修改memory数组为bool型
因为根据执行顺序,Line 101的if判断句,只有在前一个判断返回true的时候才会递归,因此若执行到memory[startIndex] = 1时,程序已经完成了遍历,memory[startIndex] = 1的情况完全没用的上。而memory用上的情况为false重复,即程序已经判断过startIndex开头无法分割。
This commit is contained in:
Qiyu Liang
2022-03-01 23:33:54 +08:00
committed by GitHub
parent 0f3c2aeec1
commit d4e3da4c3d

View File

@ -89,27 +89,26 @@ class Solution {
private:
bool backtracking (const string& s,
const unordered_set<string>& wordSet,
vector<int>& memory,
vector<bool>& memory,
int startIndex) {
if (startIndex >= s.size()) {
return true;
}
// 如果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++) {
string word = s.substr(startIndex, i - startIndex + 1);
if (wordSet.find(word) != wordSet.end() && backtracking(s, wordSet, memory, i + 1)) {
memory[startIndex] = 1; // 记录以startIndex开始的子串是可以被拆分的
return true;
}
}
memory[startIndex] = 0; // 记录以startIndex开始的子串是不可以被拆分的
memory[startIndex] = false; // 记录以startIndex开始的子串是不可以被拆分的
return false;
}
public:
bool wordBreak(string s, vector<string>& wordDict) {
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);
}
};