413. Arithmetic Slices
来源:互联网 发布:python zip函数 编辑:程序博客网 时间:2024/06/06 13:01
问题描述:
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, 97, 7, 7, 73, -1, -5, -9
The following sequence is not arithmetic.
1, 1, 2, 5, 7最终返回的结果,这个数组中有几个等差数列的子串。
问题分析:
1.暴力求解:
穷举所有的子串,检查任意两个连续的数字是否是相等的。
2.利用动态规划的思想:
1.确定状态方程:
dp[i]表示以i结尾的等差数列串个数。
2.转移方程:
dp[i]=(A[i]-A[i-1]==A[i-1]-A[i-2])?dp[i-1]+1:0;
3.结束状态:
dp[0]+dp[1]+....dp[N]。
3.代码
class Solution {public: int numberOfArithmeticSlices(vector<int>& A) { vector<int> dp(A.size(),0); for(int i=2;i<A.size();i++){ if(A[i]-A[i-1]==A[i-1]-A[i-2]){ dp[i]=dp[i-1]+1; } else dp[i]=0; } int sum=0; for (int i=0;i<A.size();i++) sum+=dp[i]; return sum; }};
阅读全文
0 0
- 413. Arithmetic Slices
- [LeetCode]413.Arithmetic Slices
- Leetcode 413. Arithmetic Slices
- Leetcode-413. Arithmetic Slices
- 413. Arithmetic Slices
- 413. Arithmetic Slices
- 【LeetCode】413. Arithmetic Slices
- 413. Arithmetic Slices
- Leetcode-413. Arithmetic Slices
- 413. Arithmetic Slices
- 413. Arithmetic Slices
- 413. Arithmetic Slices
- 413. Arithmetic Slices
- LeetCode 413. Arithmetic Slices
- 413. Arithmetic Slices 【M】
- 413. Arithmetic Slices
- Leetcode 413. Arithmetic Slices
- 413. Arithmetic Slices
- FFMPEG结构体分析:AVPacket
- 总结1-我跟书华大佬写的代码的区别
- 查找——树表的查找
- 关于 tomcat启动startup.bat一闪而过的问题
- mybatis逆向生成映射文件实体类 单元测试test 增删改查方法
- 413. Arithmetic Slices
- crack the coding interview 数组与字符串 1.2
- win7+ubuntu安装
- 虚拟化-传统-VMM
- POJ2431-C语言
- 微信 WCDB 正式开源——高效易用的移动数据库框架
- linux 常用命令
- ORACLE初学第二篇
- bzoj 4310: 跳蚤 (后缀数组+二分+ST表)