1. class Solution {
    2. private:
    3. unordered_map<long long, vector<int> > m;
    4. vector<int> nums;
    5. vector<unordered_map<long long, int> > cache;
    6. int DFS(int start, long long diff) {
    7. if (cache[start].count(diff))
    8. return cache[start][diff];
    9. long long target = (long long) nums[start] + diff;
    10. auto it = m.find(target);
    11. int count = 0;
    12. if (it != m.end()) {
    13. auto &positions = it->second;
    14. auto pos_it = upper_bound(positions.begin(), positions.end(), start);
    15. count += (positions.end() - pos_it);
    16. while (pos_it != positions.end()) {
    17. count += DFS(*pos_it, diff);
    18. ++pos_it;
    19. }
    20. }
    21. cache[start][diff] = count;
    22. return count;
    23. }
    24. public:
    25. int numberOfArithmeticSlices(vector<int> &nums_) {
    26. nums = nums_;
    27. cache.resize(nums.size());
    28. for (int i = 0; i < nums.size(); ++i) {
    29. m[nums[i]].push_back(i);
    30. }
    31. int count = 0;
    32. for (int i = 0; i < nums.size(); ++i) {
    33. for (int j = i + 1; j < nums.size(); ++j) {
    34. count += DFS(j, (long long) nums[j] - nums[i]);
    35. }
    36. }
    37. return count;
    38. }
    39. };

    时间复杂度不超过 446. 等差数列划分 II - 子序列 2021-08-11 - 图1