繁体   English   中英

求最长递增子序列 C++ 的长度

[英]Find the length of longest increasing subsequence C++

请帮我解决这个问题,当输入101 2 3 1 2 3 3 4 5 6

Output 应该是4但它是6

在所有其他测试中,该程序运行良好。

例如:

Input: 1   -10
Output: 1

Input: 2   123 123
Output: 1

Input: 2   -1245 234
Output: 2

Input: 5   1 2 3 -1 -20
Output: 3

Input: 5   1 1 2 3 1
Output: 3

Input: 5   0 0 0 1 10000
Output: 3

提前致谢!

#include <iostream>
using namespace std;

int subsequence(int arr[], int n) {

 int* length = new int[n];
 int max_length = 0;

 for (int i = 0; i < n; i++) {  
    for (int j = 0; j < i; j++) { 
       if (arr[j] < arr[i] && length[j] > length[i])
          length[i] = length[j];
    }
        length[i]++; 
 }
 for (int i = 0; i < n; i++) { 
    max_length = max(max_length, length[i]);
 }
 delete [] length;

      return max_length;
}
int main() {
  int n;
      cin >> n;
  int* arr = new int[n];
  for(int i = 0; i < n; ++i) {
      cin >> arr[i];
  }
      cout << subsequence(arr, n);

      return 0;
}

首先, length数组值被统一化,这将调用未定义的行为,在您的情况下,它碰巧可以工作,但是您应该期望数组中的任何垃圾值都将用作比较,为避免这种情况,您应该填写它与0秒。

然后,这段代码:

for (int i = 0; i < n; i++)
{
    max_length = max(max_length, length[i]);   
    std::cout << max_length << " ";    
}

这意味着,从广义上讲,只要下一个数字大于前一个数字, max_length就会增加,没有变量重置,两个序列都被计算在内:

1 2 3 1 2 3 3 4 5 6  //input sequence

1 2 3 3 3 3 3 4 5 6  //max_length value along the function
^ ^ ^         ^ ^ ^
+ + +         + + +

因此6 output。

也就是说,如果您只需要计算最大序列,那么对于这样一个简单的任务,您不需要如此复杂的代码,类似于:

int subsequence(int arr[], int n) {

    int max_length = 1; //hold the max_length
    int temp = 1;       //hold the temporary max_length

    for (int i = 0; i < n - 1; i++) {
        if(arr[i + 1] > arr[i]) { 
            temp++;     //if the next value is larger increase temp
            max_length = std::max(max_length, temp); //assign largest temp to max_length
        }
        else{     
            temp = 1;   //otherwise reset temp
        }    
    }
    return max_length;  //return max_length
}

边注:

Since you're using C++, you could upgrade your code to use C++ containers instead of C style arrays, std::vector in this case, given the variable size array.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM