446. Arithmetic Slices II

来源:互联网 发布:mac系统美图秀秀 编辑:程序博客网 时间:2024/06/07 08:25

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, 97, 7, 7, 73, -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.

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: 7Explanation: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.


求出给定序列中所有的等差子序列(最少有三个数)。用动态规划的方法。对序列中每一个数,都用一个unordered_map(所有的map组成vector,命名dp)记录用上当前数能组成的等差数列的差值,还有与之对应的不同的等差数列数目。对与1<=i<n和0<=j<i,求他们的差d=A[i]-A[j],然后在dp[j]查找是否有这个差的等差数列,有的话答案res要再加上对应的等差数列数目,因为在本来的基础上,多出了对应的等差数列数种的组合,比如[1,3,5,7],操作完前三个元素后res=1,dp[2]中键值(差值)2对应的等差数列数目为2,现在对元素7,跟5的差是2,dp[2][2]为2,所以答案res值为1+2=3,也就是[1,3,5],[3,5,7],[1,3,5,7],同时也要更新dp[i]。


代码:

class Solution{public:int numberOfArithmeticSlices(vector<int>& A){if(A.empty()) return 0;int n = A.size(), res = 0;unordered_set<int>set(A.begin(), A.end());vector<unordered_map<long long, int> > dp(n);for(int i = 1; i < n; ++i){for(int j = i-1; j >= 0; --j){long long dist = (long long)A[i] - (long long)A[j];int tmp = (dp[j].find(dist) != dp[j].end()) ? dp[j][dist] : 0;res += tmp;if(set.find(A[i] + dist) != set.end()) dp[i][dist] += tmp+1;}}return res;}};


0 0
原创粉丝点击