Java 最长递增子序列。错误在哪里?

Java 最长递增子序列。错误在哪里?,java,dynamic,Java,Dynamic,我一直在研究一个技术面试的准备工作,正在做DP问题。我遇到了最长的递增子序列问题,我直接开始做一些递归。我提出了这个解决方案,我认为这是非常直接的,但它显示出一些错误。然而,我不知道他们可能在哪里。我读了一些讨论过的解决方案,我了解它们是如何工作的,但我不明白我的错误在哪里。任何帮助都会很棒 这是我的解决办法 public static int lengthOfLIS(int[] nums) { return lengthOfLIS(nums, 0, 0, 0); }

我一直在研究一个技术面试的准备工作,正在做DP问题。我遇到了最长的递增子序列问题,我直接开始做一些递归。我提出了这个解决方案,我认为这是非常直接的,但它显示出一些错误。然而,我不知道他们可能在哪里。我读了一些讨论过的解决方案,我了解它们是如何工作的,但我不明白我的错误在哪里。任何帮助都会很棒

这是我的解决办法


    public static int lengthOfLIS(int[] nums) {
    return lengthOfLIS(nums, 0, 0, 0);
  }

  public static int lengthOfLIS(int[] nums, int carry, int index, int max){
    if(nums.length == 0){
      return 0;
    }
    if(index == nums.length - 1){
      return carry;
    }
//Checks if nums[index] is bigger than the max which is the last item to be checked.
    int temp_carry = carry;
    if(nums[index] > max){
      temp_carry++;
      max = nums[index];
    }

//Here i iterate through all the values starting from index and at the same time, 
//start a recursive call from zeroes to the next digit, and ask them to return the max between both calls.
    for(int i = index; i<nums.length; i++){
      max = Math.max(lengthOfLIS(nums, temp_carry, index+1, max), lengthOfLIS(nums, 0, index+1, nums[index+1]));
    }
    return max;
  }```



公共静态int lengthOfLIS(int[]nums){
返回长度(nums,0,0,0);
}
公共静态int lengthOfLIS(int[]nums,int进位,int索引,int最大值){
如果(nums.length==0){
返回0;
}
如果(索引==nums.length-1){
返运;
}
//检查nums[index]是否大于最后一个要检查的项目的最大值。
int temp_进位=进位;
如果(nums[索引]>最大值){
临时进位++;
max=nums[索引];
}
//这里我迭代了从索引开始的所有值,同时,
//开始一个从零到下一个数字的递归调用,并要求他们返回两次调用之间的最大值。

对于(inti=index;i,您有几个问题

首先

if(index==nums.length-1){return carry;}

这将有效地忽略数组中的最后一个值。如果最后一个值大于
max
,则不会增加
进位
,因此您的长度计数始终可能缩短1

下一个问题是您的
for
循环


还要注意,初始调用
lengthOfLIS(nums,0,0,-1)
有一个
-1
,这是因为您的序列可以从零开始…{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15},其中LIS是{0,2,6,9,11,15}(长度=6).

有什么错误?你试过调试你的代码吗?谢谢!这很清楚,我有预感我奇怪的max函数会出问题。干杯!
for(int i = index; i<nums.length; i++){
  max = Math.max(lengthOfLIS(nums, temp_carry, index+1, max), lengthOfLIS(nums, 0, index+1, nums[index+1]));
}
public int lengthOfLIS(int[] nums) {
    return lengthOfLIS(nums, 0, 0, -1);
}

public int lengthOfLIS(int[] nums, int carry, int index, int max){
    if(nums.length == 0){
        return 0;
    }

    if(nums[index] > max) {
        carry++;
        max = nums[index];
    }

    int max_carry = carry;
    for (int i = index; i < (nums.length - 1); i++) {
        int temp_carry = lengthOfLIS(nums, carry, i + 1, max);
        if (temp_carry > max_carry) {
          max_carry = temp_carry;
        }
    }
    return max_carry;
}