题目描述: 413.等差数组划分 如果一个数列至少有三个元素,并且任意两个相邻元素之差相同,则称该数列为等差数列。 例如,以下数列为等差数列: 1, 3, 5, 7, 9 7, 7, 7, 7 3, -1, -5, -9 以下数列不是等差数列。 1, 1, 2, 5, 7 数组 A 包含 N 个数,且索引从0开始。数组 A 的一个子数组划分为数组 (P, Q),P 与 Q 是整数且满足 0<=P<Q<N 。 如果满足以下条件,则称子数组(P, Q)为等差数组: 元素 A[P], A[p + 1], ..., A[Q - 1], A[Q] 是等差的。并且 P + 1 < Q 。 函数要返回数组 A 中所有为等差数组的子数组个数。 示例: A = [1, 2, 3, 4] 返回: 3, A 中有三个子等差数组: [1, 2, 3], [2, 3, 4] 以及自身 [1, 2, 3, 4]。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/arithmetic-slices 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
package DynamicPrograming;
public class Number_413 {
//向右扩展
public int numberOfArithmeticSlices(int[] A) {
int result=0;
for (int i=0;i<A.length;i++){
result+=countArithmeticSlices(A,i);
}
return result;
}
//从下标i开始 向右统计
public int countArithmeticSlices(int[] A,int i){
if (i+2>A.length)
return 0;
int dif=A[i+1]-A[i];
int j=i+1;
int count=0;
while (j+1<A.length){
if (A[j+1]-A[j]==dif){
count++;
j++;
}else
break;
}
return count;
}
//方法2 动态规划
//dp[i]表示从下标i开始 直到数组尾 的子等差数组个数
//dp[i]=dp[i+1]+count(i) count(i)表示从下标i向右统计等差数组个数
public int numberOfArithmeticSlices2(int[] A) {
int result=0;
if (A.length<=0)
return 0;
int[] dp=new int[A.length];
for (int i=A.length-1;i>=0;i--){
if (i+2>A.length)
dp[i]=0;
else {
dp[i]=dp[i+1]+countArithmeticSlices(A,i);
}
}
return dp[0];
}
}
方法1:
方法2: 该方法与方法1时间上差距很小,只不过用dp存储了部分结果