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,2,3,4]为例
1: 当我们仅考虑第一个元素1。 此时显然,由于其只有一个元素,无法构成连续序列,此时个数为0
2: 考虑前两个元素,此时个数仍为0,理由同上,元素个数未满3.
3:考虑前三元素,1,2,3相互差1,满足条件,此时我们找到个一个连续序列,此时个数为1.
4: 前四元素,1,2,3,4。 此时我们需考虑,怎么与前面3的情况建立联系? 由3的情况,我们已经得出了所有不包含最后一位(4)的数所能构成的所有结果。所以,此时我们仅需要在原先1,2,3的基础上加上所有以4位结尾的子序列的个数就可以了,听着有些绕,具体情况如下:
1,2,3: 序列个数:1
1,2,3,4 (1,2,3)序列数 + 2,3,4 + (1,2,3,4)
由此我们可以推导出动态规划的状态方程M[i]为:
if i <= 2: M[i] = 0
else: M[i] = M[i-1] + 以i位元素为末位元素的所有连续子序列的个数
代码实现如下:
public int numberOfArithmeticSlices(int[] A) {
if (A.length < 3){
return 0;
}
int result = 0;
for (int i = 2; i < A.length; i++) {
int div = A[i] - A[i-1];
int count = 0;
for (int j = i-1; j >= 0; j--){
if(A[j+1] - A[j] == div){
count ++;
} else{
break;
}
}
if(count >= 2){
result += (count-1);
}
}
return result;
}