记一次Leetcode解题--最长斐波那契子序列的长度--dp

题目

https://leetcode-cn.com/problems/length-of-longest-fibonacci-subsequence/

解题

两种办法:

  • 暴力破解, 这个没什么好说的,记得优化二分查找的范围
  • 动态规划, dp有几种写法,先看代码:
class Solution {
     public static int lenLongestFibSubseq(int[] A) {
        int size = A.length;
        int[][] dp = new int[size][size] ;
        for(int i = 0 ; i < size ; i++){
            for(int j = 0 ; j < size ;j++){
                dp[i][j] = 2 ;
            }
        }
        int left , right ;
        int res = 0 ;
        for(int i = 2 ; i < size ;i++){
            left = 0 ;
            right = i - 1 ;
            while(left < right){
                int sum = A[left] + A[right] ;
                if(sum == A[i]){
                    dp[right][i] = dp[right][i] > (dp[left][right]+1)?dp[right][i] : (dp[left][right]+1) ;
                    res = res >dp[right][i]?res:dp[right][i] ;
                    left++;
                    right--;
                }else if(sum > A[i] ){
                    right -- ;

                }else{
                    left ++ ;
                }
            }
        }
        return res ;
    }

}

最重要的是这一段,也就是状态转移方程

 if(sum == A[i]){
                    dp[right][i] = dp[right][i] > (dp[left][right]+1)?dp[right][i] : (dp[left][right]+1) ;
                    res = res >dp[right][i]?res:dp[right][i] ;
                    left++;
                    right--;
                }

这道题的dp,dp[i][j]代表以i和j为序列的最后两个下标的序列的最大长度,举个例子:
int[] a = {1,2,3,4,5,6,7,8},那么dp[1][2] 就代表以2和3为序列的最后两位的长度,这个序列就是1,2,3,长度为3;
dp[2][4]就是以3,5为最后两位的序列,序列是1,2,3,5,序列长度是4
理解了dp[i][j]的意思,这段代码就很容易看懂了.

你可能感兴趣的:(算法)