413. Arithmetic Slices

Posted bright-mark

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了413. Arithmetic Slices相关的知识,希望对你有一定的参考价值。

思路:动态规划 参考

解法一:

class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& A) {
        int res = 0, len = 2, n = A.size();
        for (int i = 2; i < n; ++i) {
            if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) {
                ++len;
            } else {
                if (len > 2) res += (len - 1) * (len - 2) * 0.5;
                len = 2;
            }
        }
        if (len > 2) res += (len - 1) * (len - 2) * 0.5;
        return res;
    }
};

解法二:

class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& A) {
        int res = 0, n = A.size();
        vector<int> dp(n, 0);
        for (int i = 2; i < n; ++i) {
            if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) {
                dp[i] = dp[i - 1] + 1;
            }
            res += dp[i];
        }
        return res;
    }
};

 

以上是关于413. Arithmetic Slices的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]413 Arithmetic Slices

[leetcode-413-Arithmetic Slices]

413. Arithmetic Slices(LeetCode)

Leetcode413. Arithmetic Slices

LeetCoce 413. Arithmetic Slices

413. Arithmetic Slices