【问题标题】:Recursion implementation of LeetCode ProblemLeetCode 问题的递归实现
【发布时间】:2019-08-15 06:04:24
【问题描述】:

问题名称 : 413. 算术切片

问题陈述 :
如果一个数列至少由三个元素组成,并且任意两个连续元素之间的差值相同,则称为算术序列。

例如,这些是等差数列:

1、3、5、7、9
7、7、7、7
3、-1、-5、-9

下面的序列不是算术的。

1、1、2、5、7

给出了一个由 N 个数字组成的零索引数组 A。该数组的切片是任意一对整数 (P, Q),满足 0

数组 A 的切片 (P, Q) 称为算术如果序列: A[P], A[p + 1], ..., A[Q - 1], A[Q] 是算术的。特别是,这意味着 P + 1

该函数应返回数组 A 中的算术切片数。

链接https://leetcode.com/problems/arithmetic-slices/


我试图找出解决上述问题的递归算法。我试图实现算法,该算法基本上采用数组的一部分并递归地解决问题,直到数组大小达到长度 == 3。在长度 == 3 时,我们检查数组是否是算术的,并基于此返回 1 或 0 .

我的解决方案

def isArithmatic(array):
    if (array[1] - array[0]) == (array[2] - array[1]):
        return True
    return False
def arithmaticSlices(array):
    if len(array) == 3:
        if isArithmatic(array):
            return 1
        return 0
    else:    
        return arithmaticSlices(array[1:]) + arithmaticSlices(array[:len(array)-1])  

我的问题:代码返回的答案小于原始答案。请帮忙。

【问题讨论】:

  • 解决方案是错误的,因为它不计算任何长度超过 3 的算术切片。
  • 感谢 GZ0 的回复。我们该如何处理这种情况?
  • 自己想不通的可以在网站上找到各种解决方案。
  • 是的,我可以,但是我已经实现了这个解决方案,我想在这个特定的算法上获得帮助,这样我就可以确保在我们研究未来的解决方案时可以改进某些事情。
  • 实际上,您的解决方案不仅忽略了一些算术切片,还计算了一些切片两次,因为array[1:]array[:-1] 有很大的重叠。如果没有一些根本性的改变,我看不到快速解决方案。

标签: python recursion dynamic-programming


【解决方案1】:

这是 LeetCode 接受的一个答案。我希望简单的逻辑是有意义的:

JavaScript 代码:

function f(A, i=2, total=0, prevSeqTotal=0){
  if (i >= A.length)
    return total

  // The number of sequences ending here is 1 (length 3)
  // plus the number ending at the previous
  // element since those all just got extended.
  if (A[i] - A[i-1] == A[i-1] - A[i-2])
    return f(A, i + 1, total + 1 + prevSeqTotal, 1 + prevSeqTotal)

  return f(A, i + 1, total, 0)
}

console.log(f([3, 1, -1, -3]))

【讨论】:

    【解决方案2】:

    考虑以下数组:

    1, 3, 5, 7
    

    您的代码计数 1, 3, 53, 5, 7。但是,它无法计算 1, 3, 5, 7(它是一个长度为 4 的算术切片)。

    【讨论】:

    • 感谢@NPE 的回复。我们可以做些什么改变来处理这些案件?任何建议。
    猜你喜欢
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 2022-08-19
    相关资源
    最近更新 更多