【LeetCode】413. Arithmetic Slices

本文介绍了一种使用动态规划方法寻找数组中等差数列的算法实现。该算法适用于包含至少三个元素的等差数列,并通过计算相邻元素间的差值来判断等差特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:
A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

For example, these are arithmetic sequence:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9

The following sequence is not arithmetic.
1, 1, 2, 5, 7

分析:
这道题要找出数组中由至少三个数组成的等差数列的个数。用动态规划来求解。设数组dp的第i位为包括第i位的等差数列的数目,数组len的第i位记录A[i]与A[i-1]之间的差。状态转移方程为:
if(len[i] == len[i-1]) dp[i] == dp[i-1]+1;
else dp[i] = 0;
最后将数组dp的全部元素加在一起就得到最终结果。
时间复杂度为O(n).
代码:

class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& A) {
        int num = 0;

        int *len = new int[A.size()];
        int *dp = new int[A.size()];
        if(A.size()<3) return 0;
        len[1] = A[1]-A[0];
        for(int i = 2;i<A.size();i++)
        {
            len[i] = A[i]-A[i-1];
            if(len[i] == len[i-1])
            {
                dp[i] = dp[i-1]+1;
            }
            else dp[i] = 0;
        }
        for(int i = 2;i<A.size();i++)
        num+=dp[i];
        return num;

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值