题目:
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;
}
};