思路:
(1)建立一個二維數組dp[i][j]:i是指下標,j是指到這個下標的差值,dp[i][j]是指到這個下標這個差值最長的序列長度
(2)如果後面某個下標到這個下標的差值與當前的差值相同,那個下標的最大差值=這個下標的差值+1
(3)此處創新點:dp[i][cha]:一個下標表示的是差值
代碼:
package com.leetCode.dp;
public class leet1027 {
/**
*
* @param args
*/
public static void main(String[] args) {
int[] arr = {20,1,15,3,10,5,8};
System.out.println(longestArithSeqLength(arr));
}
public static int longestArithSeqLength(int[] A) {
if(A==null||A.length==0) return 0;
int ans=0;
int len=10000;
int[][] dp = new int[A.length][len];
for(int i=1;i<A.length;i++)
{
for(int j=0;j<i;j++)
{
int cha = A[i]-A[j]>0?A[i]-A[j]:A[i]-A[j]+len;
dp[i][cha]=dp[j][cha]+1;
ans = Math.max(ans, dp[i][cha]);
}
}
ans++;
return ans;
}
}