413. Arithmetic Slices
来源:互联网 发布:哪些网站可以注册域名 编辑:程序博客网 时间:2024/05/21 09:50
题目:我们称一组数列为arithmetic的,当数列至少有三个数,相邻的数字间的差是相同的。换句话说,就是判断该数列是不是等差数列。给定一数组,判断该数组中可以提取多少个等差数列。例子如下:
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.
我们可以使用动态规划来解决问题。初始化数组dp,dp[i]表示在下标为0-i间的数,可以新增多少个等差数列,最后的总数为dp[0] + dp[1] + .... + dp[n-1].
dp所有元素初始化为0。部分过程如下:
代码如下:
public class Solution { public int numberOfArithmeticSlices(int[] A) { int[] dp = new int[A.length]; int sum = 0; for (int i = 2; i < dp.length; i++) { if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) { dp[i] = 1 + dp[i - 1]; 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
- BZOJ-1001 (网络流)
- Java中的ReentrantLock和synchronized两种锁定机制的对比
- 系统目录结构、ls命令 、 文件类型、alias命令
- 光源的类型
- MySql常用SQL语句
- 413. Arithmetic Slices
- 点击标题就可以选中输入框input
- JDBC基本实现原理
- 论SQL语句中的Left join-多表关系
- 基于OpenCV的视频图像组态 (13):VLC Player解码帧数据
- oracle数据库中主要文件
- poj1251 Jungle Roads
- 在CSS中,编写“新闻列表”2.0版
- NOIP2013 神经网络(拓扑)