Skip to content

Latest commit

 

History

History
93 lines (71 loc) · 2.12 KB

413.arithmetic-slices.md

File metadata and controls

93 lines (71 loc) · 2.12 KB

如果一个数列至少有三个元素,并且任意两个相邻元素之差相同,则称该数列为等差数列。

例如,以下数列为等差数列:

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]。

动态规划

最优子结构

dp[i]表示到位置 i 的等差数列长度

状态转换方程

if (A[i] - A[i-1] == A[i-1] - A[i-2]) dp[i-1] == 0 ? dp[i] = 3 : dp[i] = dp[i-1]+1 else dp[i] = 0

边界 dp[0] = dp[1] = 0

cpp

class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& A) {
        if (A.size() < 3) return 0;
        vector<int> dp(A.size(), 0);
        int diff = A[1] - A[0];
        for (int i = 2; i< A.size(); i++){
            if (A[i]- A[i-1] == diff){
                dp[i] = dp[i-1] == 0? 3: dp[i-1] +1;
            }else {
                diff = A[i]- A[i-1];
                dp[i] = 0;
            }
        }
        int ans = 0;
        for (int i = 2; i< dp.size(); i++){
            if (dp[i] > 0 && (i == dp.size()-1 || dp[i+1] == 0)){
                ans += (dp[i] - 1)*(dp[i] - 2) / 2;
            }
        }
        return ans;
    }
};

javascript

var numberOfArithmeticSlices = function (A) {
  let dp = new Array(A.length).fill(0);
  let diff = A[1] - A[0];
  for (let i = 2; i < A.length; i++) {
    if (A[i] - A[i - 1] == diff) dp[i] = dp[i - 1] == 0 ? 3 : dp[i - 1] + 1;
    else {
      diff = A[i] - A[i - 1];
      dp[i] = 0;
    }
  }
  let ans = 0;
  for (let i = 2; i < dp.length; i++) {
    if (dp[i] > 0 && (i == dp.length - 1 || dp[i + 1] == 0)) {
      ans += ((dp[i] - 2) * (dp[i] - 1)) / 2;
    }
  }
  return ans;
};