xinyu04

导航

LeetCode 413 Arithmetic Slices DP

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.

Solution

求解一个序列中等差子序列的个数。假设 \(dp[i]\) 表示以 \(i\) 结尾的序列中,符合要求的子序列个数。最开始的时候,也就是前三个数,符合要求的话则 \(dp[2]=1\). 考虑如何转移:

  • 如果 \(a[i]-a[i-1]\neq a[i-1]-a[i-2]\),显然此时:

\[dp[i]=0 \]

  • 否则,由于此时的序列比原先的序列多了一个数,也就是说前面的方案数也可以包括在此时的方案数之中,但还需要 \(+1\):即最新符合条件的 \(a[i],a[i-1],a[i-2]\)

\[dp[i] =dp[i-1]+1 \]

点击查看代码
class Solution {
private:
    int dp[5002];
public:
    int numberOfArithmeticSlices(vector<int>& nums) {
        int n = nums.size();
        if(n<3)return 0;
        if(nums[2]-nums[1]==nums[1]-nums[0])dp[2] = 1;
        int ans = 0;
        ans += dp[2];
        for(int i=3;i<n;i++){
            // dp[i]: # sols for ending with nums[i]
            if(nums[i]-nums[i-1]==nums[i-1]-nums[i-2])dp[i] = dp[i-1]+1;
            else dp[i] = 0;
            ans += dp[i];
        }
        return ans;
    }
};

posted on 2022-06-02 15:10  Blackzxy  阅读(15)  评论(0编辑  收藏  举报