# leetcode:等差數列劃分

### 題目介紹

========================================================

A = [1, 2, 3, 4]

=======================================================

### 審題:

class Solution {
public int numberOfArithmeticSlices(int[] A) {
boolean[][] S = new boolean[A.length][A.length];

int total = 0;
//basecase , 判斷長度爲3的數列是否是等差數列
for(int i = 0; i < A.length-2; i++){
if(A[i+1]-A[i] == A[i+2]-A[i+1]){
S[i][i+2] = true;
total++;
}
}

for(int len = 4; len <= A.length; len++){
for(int i = 0; i <= A.length-len; i++){
int j = i + len -1;
if(S[i][j-1] && A[j]-A[j-1] == A[j-1]-A[j-2]){
S[i][j] = true;
total++;
}
else
S[i][j] = false;
}
}
}
}


#### 複雜度分析

class Solution {
public int numberOfArithmeticSlices(int[] A) {
int total = 0;
for(int i = 0; i < A.length-2; i++){
for(int len = 2; len < A.length-i; len++){
if(A[i+len]-A[i+len-1] == A[i+len-1] - A[i+len-2])
total++;
else
break;
}
}
}
}


#### 動態規劃算法

class Solution {
public int numberOfArithmeticSlices(int[] A) {
//S[j]表示以j結尾的等差序列個數
//如果A[j+1] - A[j] = A[j] - A[j-1] , S[j+1] = S[j] + 1
//else S[j+1] = 0;
if(A.length < 3)
return 0;
int total = 0;
int[] S = new int[A.length];
if(A[2]-A[1] == A[1]-A[0]){
S[2] = 1;
total += S[2];
}

for(int i = 3; i < A.length; i++){
if(A[i] - A[i-1] == A[i-1] - A[i-2]){
S[i] = S[i-1] + 1;
total += S[i];
}
}
}
}


class Solution {
public int numberOfArithmeticSlices(int[] A) {

if(A.length < 3)
return 0;
int total = 0;
int prev = 0;
if(A[2]-A[1] == A[1]-A[0]){
prev = 1;
total += prev;
}

for(int i = 3; i < A.length; i++){
if(A[i] - A[i-1] == A[i-1] - A[i-2]){
prev = prev + 1;
total += prev;
}
else
prev = 0;
}