最长的子序列数

时间:2014-02-26 15:51:13

标签: c# java c++ c

我需要返回数组LIS的数量。

伪代码示例:

if the arr is
 int []arr = {2,4,90,-3,-2,-1,-10,-9,-8};
num of LIS is: 3
 2,4,90
 -3,-2,-1
 -10,-9,-8

示例2:

arr [] = {2,-3,4,90,-2,-1,-10,-9,-8};
num of LIS is: 4
2,4,90
-3,4,90
-3,-2,-1
-10,-9,-8

我试过这样做:

int [] A = {2,4,90,-3,-2,-1,-10,-9,-8};
    int[] dp = new int[A.length];

    for (int i = 0; i < A.length; i++) {
        dp[i] = 1;

        for (int j = 0; j <= i - 1; j++) {
            if (A[j] < A[i]) {
                dp[i] = dp[i] + dp[j];
            }
        }
        System.out.println(dp[dp.length - 1] ) ;
    }

1 个答案:

答案 0 :(得分:1)

在你的代码中,你只需继续为内部for循环中的所有查找添加dp [i]。理想情况下,您应该找到所有位置(j

int maxSizeOfSubseq = 0;
for (int i = 0; i < A.length; i++) {
    dp[i] = 1;
    maxSizeOfSubseq = 0;
    for (int j = 0; j <= i - 1; j++) {
        if (A[j] < A[i] && dp[j] > maxSizeOfSubseq ) {
            maxSizeOfSubseq = dp[j];
        }
    }
    dp[i] = dp[i] + maxSizeOfSubseq ;
             System.out.println(dp[dp.length - 1] ) ;
}


// Now find the Max Size Of Subsequence amongst all computes subsequence lengths
maxSizeOfSubseq  = 0;
for(int count = 0 ; count < dp.length; ++count)
{
  if(dp[i] > maxSizeOfSubseq )
  {
  maxSizeOfSubseq  = dp[i]
  }
}

return maxSizeOfSubseq ;