# LeetCode 446. Arithmetic Slices II - Subsequence

## 题目要求

A sequence of numbers 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 sequences:

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 subsequence slice of that array is any sequence of integers (P0, P1, …, Pk) such that 0 ≤ P0 < P1 < … < Pk < N.

A subsequence slice (P0, P1, …, Pk) of array A is called arithmetic if the sequence A[P0], A[P1], …, A[Pk-1], A[Pk] is arithmetic. In particular, this means that k ≥ 2.

The function should return the number of arithmetic subsequence slices in the array A.

The input contains N integers. Every integer is in the range of -231 and 231-1 and 0 ≤ N ≤ 1000. The output is guaranteed to be less than 231-1.

Example:

Input: [2, 4, 6, 8, 10]

Output: 7

Explanation:
All arithmetic subsequence slices are:
[2,4,6]
[4,6,8]
[6,8,10]
[2,4,6,8]
[4,6,8,10]
[2,4,6,8,10]
[2,6,10]
Subscribe to see which companies asked this question

## 解题代码

    public int numberOfArithmeticSlices(int[] A) {
int re = 0;
HashMap<Integer, HashMap<Long, Integer>> diffMaps = new HashMap<>();
for (int i = 0; i < A.length; i++) {
HashMap<Long, Integer> diffMap = new HashMap<>();
diffMaps.put(i, diffMap);
int num = A[i];
for (int j = 0; j < i; j++) {
if ((long) num - A[j] > Integer.MAX_VALUE)
continue;
if ((long) num - A[j] < Integer.MIN_VALUE)
continue;
long diff = (long) num - A[j];
int count = diffMaps.get(j).getOrDefault(diff, 0);
diffMaps.get(i).put(diff, diffMaps.get(i).getOrDefault(diff, 0) + count + 1);
re += count;
}
}
return re;
} 12-10 773

#### leetcode 446. Arithmetic Slices II - Subsequence 等差序列的数量 + 一个很值得学习的DP动态规划做法

12-06 1065

#### Leetcode-446. Arithmetic Slices II - Subsequence

11-13 313

#### 446. Arithmetic Slices II - Subsequence

11-10 323

#### [Leetcode] 446. Arithmetic Slices II - Subsequence 解题报告

01-15 78

#### Leetcode 446.等差数列划分II 子序列

03-01 38

#### Leetcode 446

11-27 263

#### Leetcode 413 & 446

10-29 2331

#### map+DP leetcode446

02-14 51

#### [LeetCode] 446. Arithmetic Slices II - Subsequence

02-25 256

#### 446. Arithmetic Slices II - Subsequence***

10-15 4341

#### LeetCode 413.Arithmetic Slices 解题报告

12-02 418

#### python leetcode 446. Arithmetic Slices II - Subsequence

01-07 191

#### Arithmetic Slices II - Subsequence ©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 点击重新获取   扫码支付