Python 10-Line Easy Understanding.

  • 0

    Same idea with "".

    Iterate trough A and for each number A[i], get the diff with all the previous nums A[j], 0<=j<i. If A[j] also has the same diff, then it means we've found an Arithmetic Slice.

        def numberOfArithmeticSlices(self, A):
            result, dp = 0, [{} for _ in A]
            for i in xrange(len(A)):
                for j in xrange(i):
                    diff = A[i] - A[j]
                    dp[i][diff] = dp[i].get(diff, 0) + 1
                    if diff in dp[j]:
                        result += dp[j][diff]
                        dp[i][diff] += dp[j][diff]
            return result
    # runtime 878ms

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.