Leetcode动态规划 等差数列划分

An integer array 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, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.
Given an integer array nums, return the number of arithmetic subarrays of nums.
A subarray is a contiguous subsequence of the array.

思路
这道dp题好不容易会做,结果这个bug改到我快吐了,说明基本功不扎实…
题外话,题目中的difference原来还有“差”的意思(到处都是知识盲区)
整体思路就是用dp数组记录当前等差的连续元素数,当差值不相等时,需要结算一下前一个元素区间。在循环结束后,不要忘记结算最后一个元素区间~

代码

class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& nums) {
        int len = nums.size();
        if(len < 3) return 0;
        int dp[5005] = {1, 2};
        int sum = 0, temp = nums[1] - nums[0];

        for(int i = 2; i < len; i++)
        {
            if(nums[i] - nums[i-1] == temp)
                dp[i] = dp[i-1] + 1;
            else
            {
                if(dp[i-1] >= 3)
                    sum += 0.5*(dp[i-1]*dp[i-1]-3*dp[i-1]+2);
                dp[i] = 2;
                temp = nums[i] - nums[i-1];
            }
        }
        if(dp[len-1] >= 3)
            sum += 0.5*(dp[len-1]*dp[len-1]-3*dp[len-1]+2);

        return sum;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值