Week Training: 413 Arithmetic Slices

来源:互联网 发布:删除不了windows.old 编辑:程序博客网 时间:2024/06/10 17:53

Many ways to do, using dp, we can let dp[i] be the number of slices until i in the array, so the state transformation is dp[i]=dp[i-1]+1, when the new number is able to make a arithmetic slice with before. The total number is to add numbers of each position until the last element.

class Solution {public:    int numberOfArithmeticSlices(vector<int>& A) {        int l = A.size();        vector<int> dp(l);        int num = 0;        for(int i=0;i<l;i++){            dp[i]=0;        }        for(int i=2;i<l;i++){            if(A[i-1]-A[i-2]==A[i]-A[i-1]){                dp[i] = dp[i-1]+1;            }            num += dp[i];        }        return num;    }};

 

原创粉丝点击