8.22 - hard - 86

2017-08-23  本文已影响0人  健时总向乱中忙

446. Arithmetic Slices II - Subsequence

一道dp的题目

class Solution(object):
    def numberOfArithmeticSlices(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        total = 0
        dp = [collections.defaultdict(int) for item in A]
        # dp[i][j] stores the number of arithmetic slices (including those with only length 2) whose constant difference is j ending at i
        for i in range(len(A)):
            for j in range(i):
                gap = A[i] - A[j]
                dp[i][gap] += 1
                if gap in dp[j]:
                    dp[i][gap] += dp[j][gap]
                    total += dp[j][gap]
        return total
        
上一篇 下一篇

猜你喜欢

热点阅读