413. Arithmetic Slices

来源:互联网 发布:python zip函数 编辑:程序博客网 时间:2024/06/06 13:01

问题描述:

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, 97, 7, 7, 73, -1, -5, -9

The following sequence is not arithmetic.

1, 1, 2, 5, 7
最终返回的结果,这个数组中有几个等差数列的子串。

问题分析:

1.暴力求解:

穷举所有的子串,检查任意两个连续的数字是否是相等的。

2.利用动态规划的思想:

   1.确定状态方程:

     dp[i]表示以i结尾的等差数列串个数。

   2.转移方程:

     dp[i]=(A[i]-A[i-1]==A[i-1]-A[i-2])?dp[i-1]+1:0;

   3.结束状态:

    dp[0]+dp[1]+....dp[N]。

3.代码

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

原创粉丝点击