413. Arithmetic Slices
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
A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 <= P < Q < N.
A slice (P, Q) of array A is called arithmetic if the sequence:
A[P], A[p + 1], …, A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q.
The function should return the number of arithmetic slices in the array A.
Example:
A = [1, 2, 3, 4]
return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.
方法1: dynamic programming
思路:
在一个长度为len的array基础上,如何才能知道len + 1是否能够继续形成等差数列?我们只需要检查A[i] - A[i - 1] == A[i - 1] - A[i - 2]是否成立。如果成立的话在之前数量的基础上转移过来并+1,因为此时dp[i - 1]所有的等差数列都能被延长,并且最后三个数字形成一个extra等差数列。因此,dp应该记录的是以 i 位置结尾能够形成的等差数列总数。
dp(n) : 以 i 位置结尾能够形成的等差数列总数。
initialize: 循环从2开始,前两个应该是0(不能形成等差)。
transfer: if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) dp[i - 1] = dp[i] + 1,同时累加到res。
return: res。
Complexity
Time complexity: O(n)
Space complexity: O(n)
class Solution {
public:
int numberOfArithmeticSlices(vector<int>& A) {
if (A.size() <= 2) return 0;
int res = 0, n = A.size();
vector<int> dp(n, 0);
for (int i = 2; i < n; i++) {
if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) dp[i] = dp[i - 1] + 1;
res += dp[i];
}
return res;
}
};
本文介绍了一种使用动态规划方法来计算数组中等差数列切片总数的算法。通过检查连续元素间的差值,判断是否能形成等差数列,进而更新动态规划数组,最终返回所有可能的等差数列切片数量。
1269

被折叠的 条评论
为什么被折叠?



