Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 446. Arithmetic Slices II - Subsequence

Rain Hu

446. Arithmetic Slices II - Subsequence


一、題目

Given an integer array nums, return the number of all the arithmetic subsequences of nums. 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.

Example 1:

Example 2:

Constraints:


二、分析

三、解題

1. DP

int numberOfArithmeticSlices(vector<int>& nums) {
    int n = nums.size();
    int res = 0;
    vector<unordered_map<int,long long>> dp(n);  // dp[index][diff]
    for (int i = 2; i < n; i++) {
        unordered_map<int,int> map;
        for (int j = 0; j < i; j++) {
            long long diff = (long long)nums[i] - (long long)nums[j];
            long long target = nums[j] - diff;   // check target is in the range  
            if (target >= INT_MIN && target <= INT_MAX){
                if (map.count(target)) dp[i][diff] += map[target];  // 三個一組的子序列
                if (dp[j].count(diff)) dp[i][diff] += dp[j][diff];  // 三個以上的子序列
            }
            map[nums[j]]++;
        }
    }
    for (int i = 0; i < n; i++) {
        for (auto m : dp[i]) {
            res += m.second;
        }
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2469. Convert the Temperature
Next
[LeetCode] 2488. Count Subarrays With Median K