python leetcode 446. Arithmetic Slices II - Subsequence

由于求的是有多少种 很容易想到用DP做 难点在于如何设置及更新DP
假设dp[i][j]是在A[:i+1]差值为j的所有长度为2的数组数量
譬如[2,4,6,8]
i=3时 dp[:3]=[{},{2: 1},{4: 1, 2: 2}]
j=2时 d=A[i]-A[j]=2 d在dp[j]中那么更新dp[i][d]+=dp[j][d] (2,([2,4],[4,6]))=3 ([2,4],[4,6],[6,8]) 相应的total结果+=dp[j][d] ([2,4,6],[4,6,8])

class Solution:
    def numberOfArithmeticSlices(self, A):
        """
        :type A: List[int]
        :rtype: int
        """ 
        n = len(A)
        total=0
        dp=[{} for _ in range(n)]
        for i in range(n):
            for j in range(i):
                d =  A[i]-A[j]
                if d in dp[i]:
                    dp[i][d]+=1
                else:
                    dp[i][d]=1 
                if d in dp[j]:
                    dp[i][d]+=dp[j][d]
                    total+=dp[j][d]
        return total

你可能感兴趣的:(leetcode,python,leetcode,python)