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
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; }
相关文章推荐
- 413. Arithmetic Slices
- 413. Arithmetic Slices
- [LeetCode]413. Arithmetic Slices
- 413. Arithmetic Slices
- leetcode 413. Arithmetic Slices
- 413. Arithmetic Slices
- 413. Arithmetic Slices
- Leetcode 413. Arithmetic Slices
- 413. Arithmetic Slices
- 【leetcode】【Medium】【413. Arithmetic Slices】【Math】【Dynamic programming】
- leetcode 413. Arithmetic Slices
- Leetcode-413. Arithmetic Slices
- LeetCode 413. Arithmetic Slices
- LeetCode笔记:413. Arithmetic Slices
- 【LeetCode】413. Arithmetic Slices
- LeetCode题目:413. Arithmetic Slices
- 413. Arithmetic Slices
- Leetcode 413. Arithmetic Slices 所有等差序列 解题报告
- LeetCode 413. Arithmetic Slices
- [leetcode 413. Arithmetic Slices]medium|week 12