[LeetCode] 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]

这道题是之前那道Arithmetic Slices的延伸,但是比较简单是因为要求等差数列是连续的,而这道题让我们求是等差数列的子序列,可以跳过某些数字,不一定非得连续,那么难度就加大了,但还是需要用DP来做。我们建立一个一维数组dp,数组里的元素不是数字,而是放一个哈希表,建立等差数列的差值和其长度之间的映射。我们遍历数组中的所有数字,对于当前遍历到的数字,又从开头遍历到当前数字,计算两个数字之差diff,如果越界了不做任何处理,如果没越界,我们看dp[i]中diff的差值映射自增1,然后我们看dp[j]中是否有diff的映射,如果有的话,说明此时已经能构成等差数列了,将dp[j][d]加入结果res中,然后再更新dp[i][d],这样等遍历完数组,res即为所求,我们用题目中给的例子数字[2,4,6,8,10]来看:

2    4    6    8   10    
    2-1  4-1  6-1  8-1
         2-2  4-1  6-1 
              2-3  4-2

最终累计出来的结果是上面红色的数字1+2+1+3=7,分别对应着如下的等差数列:

1:[2,4,6]

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

1:[2,6,10]

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

class Solution {
public:
    int numberOfArithmeticSlices(vector<int>& A) {
        int res = 0, n = A.size();
        vector<unordered_map<int, int>> dp(n);
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < i; ++j) {
                long long diff = (long long)A[i] - (long long)A[j];
                if (diff > INT_MAX || diff < INT_MIN) continue;
                int d = (int)diff;
                if (!dp[i].count(d)) dp[i][d] = 0;
                ++dp[i][d];
                if (dp[j].count(d)) {
                    dp[i][d] += dp[j][d];
                    res += dp[j][d];
                }
            }
        }
        return res;
    }
};

本文转自博客园Grandyang的博客,原文链接:算数切片之二 - 子序列[LeetCode] Arithmetic Slices II - Subsequence ,如需转载请自行联系原博主。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值