当前位置:网站首页>LeetCode 413.等差数列划分
LeetCode 413.等差数列划分
2022-08-09 15:45:00 【老乐大魔王】
代码:
int numberOfArithmeticSlices(vector<int>& nums) {
int n=nums.size();
if(n<=2)return 0;
vector<int> dp(n);
for(int i=2;i<n;++i){
if(nums[i]-nums[i-1]==nums[i-1]-nums[i-2]){
dp[i]=dp[i-1]+1;
}
}
return accumulate(dp.begin(),dp.end(),0);
}
解题思路:
定义状态:dp[i]表示从nums[0]到nums[i](并且以nums[i]为结尾,这句话是关键)的区间内所含有的子等差数列个数
状态转移方程:if(dp[i]-dp[i-1]==dp[i-1]-dp[i-2])dp[i]=dp[i-1]+1
这段代码表示如果nums[i]满足区间(nums[0],nums[i-1])
的差值,也就表示出现了一个新的等差区间{nums[i-2],nums[i-1],nums[i]}
,那么dp[i]的值等于在dp[i-1]的基础上+1,若nums[i]不满足区间(nums[0],nums[i-1])
的差值,那么以nums[i]为结尾的等差序列是不存在的,因此此时dp[i]的值=0
边栏推荐
- C语言小游戏—扫雷
- ECCV 2022 | BMD: 面向无源领域自适应的类平衡多中心动态原型策略
- 2.1、基于并行上下文注意网络的场景文本图像超分辨率
- std::uniform_real_distribution的一个bug引发的服务器崩溃
- 良匠-手把手教你写NFT抢购软(一)
- HR to get the entry date RP_GET_HIRE_DATE
- uniapp project construction
- 【嵌入式入门篇】嵌入式0基础沉浸式刷题篇1
- No need to pay for the 688 Apple developer account, xcode13 packaged and exported ipa, and provided others for internal testing
- B50 - 基于51单片机的儿童成长管理系统
猜你喜欢
三.两数交换 空指针 && 野指针 解引用问题
Smart Light Pole Gateway Smart Transportation Application
数据可视化的类别及其重要性
A42 - 基于51单片机的洗衣机设计
A48基于NRF24L01的无线心率血氧体温检测
Reasons for slow startup of IDEA (1)
B45 - 基于STM32单片机的家庭防火防盗系统的设计
国星光电吉利产业园项目主体结构全面封顶,将重点生产 RGB 小间距、Mini LED、TOP LED 等产品
Volatile:JVM 我警告你,我的人你别乱动
B024 – STM32温湿度控制体温检测烟雾报警系统
随机推荐
Vim practical skills_2. Normal mode and insert mode
现在,怎么挑选舞台租赁LED显示屏?
The article details of the qiucode.cn website realize the code block can be copied by clicking the button
OpenCV 图像变换之 —— 拉伸、收缩、扭曲和旋转
The Chinese Academy of Sciences slaps Google in the face: ordinary computers catch up with quantum superiority, and can solve calculations that would have taken 10,000 years in a few hours...
Became CTO, was killed by my boss in 6 months, I lost 10 million
Redis Cache Expiration and Retirement Policy
自定义过滤器和拦截器实现ThreadLocal线程封闭
国星光电吉利产业园项目主体结构全面封顶,将重点生产 RGB 小间距、Mini LED、TOP LED 等产品
网络——IPV4地址(二)
TMin - TMin是否产生溢出
苹果开发者账号 申请 D-U-N-S 编号
B024 – STM32温湿度控制体温检测烟雾报警系统
nacos控制台权限管理
Qt学习第二天
Using Prometheus skillfully to extend the kubernetes scheduler
uniapp 项目搭建
August 9, 2022: Build .NET apps in C# -- use the Visual Studio Code debugger to interactively debug .NET apps (won't, fail)
网络——涉及的相关协议和设备汇总
ESP8266-Arduino编程实例-MQ-5液化天然气传感器驱动