From d4e3da4c3db7729441397b7555b5a26b62fb8e2c Mon Sep 17 00:00:00 2001 From: Qiyu Liang <61932152+Guicai996@users.noreply.github.com> Date: Tue, 1 Mar 2022 23:33:54 +0800 Subject: [PATCH] =?UTF-8?q?Update=200139.=E5=8D=95=E8=AF=8D=E6=8B=86?= =?UTF-8?q?=E5=88=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 删除原Line 102,修改memory数组为bool型 因为根据执行顺序,Line 101的if判断句,只有在前一个判断返回true的时候才会递归,因此若执行到memory[startIndex] = 1时,程序已经完成了遍历,memory[startIndex] = 1的情况完全没用的上。而memory用上的情况为false重复,即程序已经判断过startIndex开头无法分割。 --- problems/0139.单词拆分.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/problems/0139.单词拆分.md b/problems/0139.单词拆分.md index 1653a81a..e04cb173 100644 --- a/problems/0139.单词拆分.md +++ b/problems/0139.单词拆分.md @@ -89,27 +89,26 @@ class Solution { private: bool backtracking (const string& s, const unordered_set& wordSet, - vector& memory, + vector& 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& wordDict) { unordered_set wordSet(wordDict.begin(), wordDict.end()); - vector memory(s.size(), -1); // -1 表示初始化状态 + vector memory(s.size(), 1); // -1 表示初始化状态 return backtracking(s, wordSet, memory, 0); } };