Leetcode_413_ArithmeticSlices_数组中等差递增子区间的个数

package DP;

/**
 * 数组中等差递增子区间的个数
 * exm:
 * A = [0, 1, 2, 3, 4]
 *
 * return: 6, for 3 arithmetic slices in A:
 *
 * [0, 1, 2],
 * [1, 2, 3],
 * [0, 1, 2, 3],
 * [0, 1, 2, 3, 4],
 * [ 1, 2, 3, 4],
 * [2, 3, 4]
 * 解释:
 * dp[i]表示以 A[i] 为结尾的等差递增子区间的个数。
 * 状态转移:dp[i] = dp[i-1] + 1,条件是满足A[i] - A[i-1] == A[i-1] - A[i-2]
 */
public class _413_ArithmeticSlices {
    // 1. dp
    public int numberOfArithmeticSlices(int[] A) {
        if (A == null || A.length == 0){
            return 0;
        }
        int n = A.length;
        int[] dp = new int[n];

        for (int i = 2; i < n; i++){
            if (A[i] - A[i-1] == A[i-1] - A[i-2]){
                dp[i] = dp[i-1] + 1;
            }

        }
        int sum = 0;
        for (int tmp : dp){
            sum += tmp;
        }
        return sum;
    }

    // 2. dp简化
    public int numberOfArithmeticSlices2(int[] A){
        if (A == null || A.length == 0){
            return 0;
        }
        int cur = 0;
        int sum = 0;
        for (int i = 2; i < A.length; i++){
            if (A[i] - A[i-1] == A[i-1] - A[i-2]){
                cur += 1;
                sum += cur;
            }else{
                cur = 0;
            }
        }
        return sum;
    }
    public static void main(String[] args) {
        int[] A = {0, 1, 2, 3, 4};
        System.out.println(new _413_ArithmeticSlices().numberOfArithmeticSlices(A));
    }
}

你可能感兴趣的:(Leetcode刷题之动态规划)