Leetcode 413:算术切片 Python
你好,我正在尝试解决 Leetcode 413:算术切片。我试图从强力递归解决方案开始。
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
def slices(nums: List[int], i: int):
if (i < 2):
return 0
if nums[i] - nums[i-1] == nums[i-1] - nums[i-2]:
return 1 + slices(nums, i -1)
else:
return slices(nums, i-1)
if len(nums) < 3:
return 0
return slices(nums, len(nums)-1)
这对于测试用例 [1,2,3,4]
不起作用(它返回 2 而不是 3)。在我的脑海中,我知道它不起作用,因为当调用该函数时, 1 + slices([1,2,3], 2)
返回 2。我如何修复我的代码以获得来自整个数组[1,2,3,4]
的算术切片?
Hi I'm trying to solve Leetcode 413: Arithmetic slices. I'm trying to start with a brute force recursive solution.
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
def slices(nums: List[int], i: int):
if (i < 2):
return 0
if nums[i] - nums[i-1] == nums[i-1] - nums[i-2]:
return 1 + slices(nums, i -1)
else:
return slices(nums, i-1)
if len(nums) < 3:
return 0
return slices(nums, len(nums)-1)
This doesn't work for the test case [1,2,3,4]
(it returns 2 instead of 3). In my head I know it doesn't work because when the function is called, 1 + slices([1,2,3], 2)
returns 2. How can I fix my code to get the arithmetic slice coming from the entire array [1,2,3,4]
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了解决这个问题,你必须采取两个步骤。
首先你必须找到所有可能的连续子数组
您必须检查它们是否是算术切片。
一个可以理解的解决方案,它不具有内存和时间效率,如下所示:
但是一个更难掌握但具有内存和时间效率的解决方案如下所示(您仍然可以用循环替换递归调用,我认为您会得到这样做效果更好):
For solving this problem you have to take two steps.
First you have to find all possible contiguous sub-arrays
You have to check them, if they are arithmetic slices.
An understandable solution which is not memory and time efficient is as below:
But a solution that is little more harder to grasp but is memory and time efficient is as bellow(You could still replace the recursive call with a loop and I think you would get better results doing so):