原题链接:https://leetcode-cn.com/problems/arithmetic-slices/
采用动态规划
dp[i][j]表示从i到j的子数组是否为等差数组
转移方程:
dp[j]=dp[j-1]+1; //如果是等差A[j]与前面构成等差
代码:
inline bool isArithmeticSlices(vector<int> &A,int j){
return A[j]-A[j-1]==A[j-1]-A[j-2];
}
int numberOfArithmeticSlices(vector<int>& A) {
int size=A.size();
if(size<3) return 0;
vector<int> dp(size,0);
int count=0;
for(int i=0,j=i+2;i<size-2;i++,j++){
if(isArithmeticSlices(A,j))
dp[j]=dp[j-1]+1;
count+=dp[j];
}
return count;
}
优化:不使用dp数组,因为每次循环只和dp,dp[j-1]有关
inline bool func(vector<int> &A,int j){
return A[j]-A[j-1]==A[j-1]-A[j-2];
}
int numberOfArithmeticSlices(vector<int>& A) {
int size=A.size();
if(size<3) return 0;
int dp=0;
int count=0;
for(int i=0,j=i+2;i<size-2;i++,j++){
if(func(A,j))
dp=dp+1;
else
dp=0;
count+=dp;
}
return count;
}