Leetcode446。算术切片II-子序列

时间:2018-12-02 05:39:00

标签: python algorithm recursion arithmetic-expressions

这是有关leetcode的问题。我正在使用递归策略,但是超过了时间限制。那么有人可以给我一些建议来改善我的算法吗?非常感谢。

这是问题链接: https://en.wikipedia.org/wiki/RTEMS

有我的原始密码:

class Solution:
def numberOfArithmeticSlices(self, A):
    """
    :type A: List[int]
    :rtype: int
    """
    A = sorted(A) 
    self.n = 0
    for x in range(len(A)):
        for y in range(x+1, len(A)):
            if A[-1] - A[y] < A[y] - A[x]: 
                break
            self.helper(y+1, A[y]-A[x], A, A[y])
    return self.n

# i represents the next index we should step through from, k represents 
# the current difference, prev represents the previous element so we 
# could calculate the current difference    

def helper(self, i, k, A, prev):   
    if i == len(A):
        return 
    for x in range(i, len(A)):
        if A[x] - prev == k:
            self.n += 1
            self.helper(x+1, k, A, A[x])
        elif A[x] - prev > k:
            return 

0 个答案:

没有答案