LeetCode413 Arithmetic Slices| 动态规划

题目描述

  1. Arithmetic Slices QuestionEditorial Solution My Submissions
    Total Accepted: 4238
    Total Submissions: 7915
    Difficulty: Medium
    Contributors: XiangyuLi926
    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.

算法分析

这道题目是median难度的,作为我集中训练动态规划的热身题,这道题很快的就可以解出来。我们看一下例子其实不难看出规律,
当A = [1,2,3] 时, n =1 ;
当A = [1,2,3,4]时, 在序列里面多了一个符合的数字,那么情况就多加了[2,3,4]和[1,2,3,4]。我们不难推测出,当再多一个数字5时,情况应当多了[3,4,5] [2,3,4,5] [1,2,3,4,5] ,也就是说,当这个新增一个符合的数字时,他增多的序列个数是等于 当前位置-序列起始位置-1 的。
我们不难可以写出状态转移方程:

定义:
- count 用来数 同一个序列的个数
- pre 表示该序列的公差
- cur 表示当前数字与上一个数字的差值
- result[] 数组拿来储存当前位置最大的序列个数(实际上也可以不需要,但是为了更好理解,这里用到了数组)

if(cur==pre)
if(count++>1) //保证序列内的个数大于2
result[i] = result[i-1] + count -1;
else {
pre = cur;
count =1;
result[i] = result[i-1];
}

int numberOfArithmeticSlices(vector<int>& A) {
    if(A.size()<3) return 0;
    vector<int> result(A.size());
    int pre=1000000000000, cur,count= 0 ;

    for(int i = 1 ; i < A.size() ; i++){
        cur = A[i]-A[i-1];
        if(cur!=pre){
            count = 1;
            pre = cur;
            result[i] = result[i-1];
        }
        else{
            count++;
            if(count>1){
                result[i] = result[i-1]+count-1;
            }
        }
    }
    for(int i = 0 ; i < result.size() ;i++) cout<<result[i]<<endl;
    return result[result.size()-1];     
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值