python - 递归程序打印但没有返回正确的值
问题描述
我正在尝试解决一个名为 word break https://leetcode.com/problems/word-break/的 leetcode 问题
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,确定 s 是否可以分割成一个或多个字典单词的空格分隔序列。
我可以打印适合解决方案的不同分词符,但是在返回我的代码时总是返回 None。我该如何修复它,使其res
成为一个数组,其中包含创建 s 的字典中的不同单词
import sys;
class Solution:
def wordBreak(self, s, wordDict):
res = self.driver(s, 0, len(s), wordDict, [])
print(res)
def driver(self, text, start, end, wordDict, res):
if text[start:end] == None:
return res
elif text[start:end] in wordDict:
result = text[start:end]
res.append(result)
print(res)
return self.driver(text, end, len(text), wordDict, res)
else:
for i in range(start, end):
self.driver(text, start, i, wordDict, res)
解决方案
像这样的递归问题很常见,如果不让递归完成工作,您会使其变得比必要的更难。尽管@blhsing 的解决方案很优雅(+1),但让我们使用您的设计,但要简化它:
class Solution:
def wordBreak(self, s, wordDict):
return self.wordBreak_recursive(s, 0, len(s), wordDict)
def wordBreak_recursive(self, s, start, end, wordDict):
for index in range(start + 1, end + 1):
if s[start:index] in wordDict and (index == end or self.wordBreak_recursive(s, index, end, wordDict)):
return True
return False
不需要收集段,res
因为要求是关于拟合是否可能的布尔结果:
solver = Solution()
print(solver.wordBreak("leetcode", ["leet", "code"]))
print(solver.wordBreak("applepenapple", ["apple", "pen"]))
print(solver.wordBreak("catsandog", ["cats", "dog", "sand", "and", "cat"]))
输出
> python3 test.py
True
True
False
>
同样,我们不需要找到所有解决方案,只需找到一个即可。
最后,如果您的递归方法返回一个值,那么任何时候我们递归调用它时,我们通常需要处理该返回值,而不是忽略它——即使递归方法通过修改其调用者环境中的变量来保护结果。否则,也许它不应该返回任何东西。
推荐阅读
- testing - 使用柏树重定向
- eclipse - 在 Windows 8.1 上的 Eclipse Oxygen 4.7 中安装 Google Cloud Tools Plugin 1.6.1 时出错
- android - 使用 Gradle 插件 3.1.2 改造 2.4.0
- xamarin - 如何在 xamarin 中将 .aar 文件转换为 .dll 时修复警告,因为它没有生成所有必需的类/接口
- python - 熊猫,合并 2 个数据框
- django - 仅当用户登录时从 Angular 发送 Post-requests 时禁止 Django 403
- android - 什么是 CTS 主机配置?
- xml - XQL 选择以下元素
- syntax - VS Code 将正确的 Flex Box 语法高亮显示为错误
- c - 打印垂直直方图