LC 413. Arithmetic Slices

1.题目描述

413. Arithmetic Slices

Medium

47095

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,5

有1,2,3,4,5,; 1,2,3,4,; 2,3,4,5; 1,2,3; 2,3,4; 3,4,5 共6个等差数列。虽然1,3,5也是等差数列但它不满足数字之间连续的条件所以它不算入。

2.解题思路

动态规划问题。用一个二维的int dp[ 2 ][ num ] 数组记录中间状态。num是给的数字的个数。

dp[ 0 ][ i ] 第一行用来记录到第i个数有多少个等差数列

dp[ 1 ][ i ]第二行用来记录当前“等差数列”里有多少个连续的数(这里之所以打引号是因为有时候两个数不构成等差数列,此时dp[ 1 ][ i ]的值为2 )

因为题目要求的连续性,可以得到以下等式:

若第i个数和前面不构成等差数列(打断了当前等差数列):

dp [ 0 ][ i ]  = dp[ 0 ][ i-1 ]   ;等差数列数量没有变

dp [ 1 ][ i ] = 2  当前不构成等差数列,连续数字的个数为2

同时要更新公差为 第i个数 - 第i-1个数

若第i个数和前面构成等差数列:

dp[ 0 ][ i ] = dp[ 0 ][ i-1 ] + dp[ 1 ][ i-1 ] - 1;
dp[ 1 ][ i ] = dp[ 1 ][ i-1 ] + 1;

不用更新等差数列公差

最后返回dp[ 0 ][ num ] 即可

3.实现代码

class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& A) {
        int num = A.size();
        if (A.size()<3) return 0;
        int dp[2][num];//第一行用来记录到A[i]有几个等差数列,第二行用来记录目前等差数列有几个连续的等差数
        memset(dp, 0, sizeof(dp));
        int d = A[1]-A[0];//公差
        dp[0][0] = dp[0][1] = 0;
        dp[1][0] = 1;
        dp[1][1] = 2;
        for (int i=2; i<num; i++) {
            if (A[i]-A[i-1] == d)//前面是一个等差数列,加入的数还构成等差数列的情况
            {
                dp[0][i] = dp[0][i-1] + dp[1][i-1] - 1;
                dp[1][i] = dp[1][i-1] + 1;
            }
            else //与前面的数不构成等差数列
            {
                dp[0][i] = dp[0][i-1];//到这个数为止的等差数列个数不变
                dp[1][i] = 2;//没有构成等差数列,所以“等差数列”里连续的数为2个
                d = A[i] - A[i-1];//更新公差d
            }
        }
        return dp[0][num-1];
    }
};

猜你喜欢

转载自blog.csdn.net/qq_41814429/article/details/84952384