您的位置:首页 > 其它

413. Arithmetic Slices

2018-01-05 08:10 155 查看
1. Description

Given an array, calculate the number of arithmetic slices in the array.

2. Solution

Dynamic Programming.

Implement an array dp
, of which n is the length of the array.

dp[i] refers to the number of arithmetic slices ending at the position i.

dp[0]=dp[1]=0.

dp[i] = dp[i-1]+1, if x[i] + x[i-2] = 2 * x[i-1].

The answer is the sum of the array dp.

3. Code

int numberOfArithmeticSlices(vector<int>& A) {
int n = A.size();
if(n<=1) return 0;
int dp
;
dp[0]=0;
dp[1]=0;
int ans=0;
for(int i=2;i<n;i++){
dp[i]=0;
if(A[i]+A[i-2]==2*A[i-1])
dp[i]=dp[i-1]+1;
ans+=dp[i];
}
return ans;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息