簡體   English   中英

如何從給定數組打印最長遞增子序列(LIS)?

[英]How to print Longest Increasing Subsequence(LIS) from a given array?

我可以通過普通函數和遞歸函數打印 LIS 的長度。 但是我想在 C++ 中的給定數組中打印 LIS 子序列的索引。

這是我查找 LIS 長度的函數:

int lis( int *arr, int n )
{
   int *lis, i, j, max = 0;
   lis = (int*) malloc ( sizeof( int ) * n );
   for ( i = 0; i < n; i++ )
      lis[i] = 1;
   for ( i = 1; i < n; i++ )
      for ( j = 0; j < i; j++ )
         if ( arr[i] > arr[j] && lis[i] < lis[j] + 1)
            lis[i] = lis[j] + 1;
   for ( i = 0; i < n; i++ )
      if ( max < lis[i] )
         max = lis[i];
   /* Free memory to avoid memory leak */
   free( lis );
   return max;
}

這里array[10]={7 6 2 3 4 1 8 5 9 10}

這里LIS Length=6

我想打印數字的索引{2 3 4 6 8 9} (它不是序列,它是數組索引,我想打印) array[10]中序列的索引array[10]

在為每個索引計算 lis 后,取一個等於 max 的 tmp 值,在 lis 數組上向后走,每次找到等於 max 的元素時,將該索引添加到答案中並減少 tmp。 因此,您將以相反的順序獲得索引數組。

示例代碼:

int tmp = max;
std::vector<int> indexes;
for( i = n - 1; i >= 0; --i )
   if( lis[ i ] == tmp )
   {
      indexes.push_back( i );
      --tmp;
   }
std::reverse( indexes.begin(), indexes.end());

要按順序打印,您可以使用遞歸方法:調用:printLIS(lis, lis.length -1, arr, max)

public static void printLIS(int[] lis, int lisIndex, int[] arr, int max) {
    if(max == 0) {
        return;
    }
    if(lis[lisIndex] == max) {
        printLis(lis,lisIndex-1, arr, max-1);
        System.out.print(arr[lisIndex] + " ");
    } else {
        printLis(lis,lisIndex-1, arr, max);
    }

}
void solution() {
  int n;
  cin >> n;
  vector<int> v(n);
  for (int &x : v) cin >> x;
  vector<int> dp(n, 1);
  int i = 0, j = 1;
  vector<int> par(n);
  for (int i = 0; i < n; i++) {
     par[i] = i;
  }
  for (int j = 1; j < n; j++) {
     for (int i = 0; i < j; i++) {
        if (v[j] > v[i] && dp[j] < dp[i] + 1) {
           dp[j] = dp[i] + 1;
           par[j] = i;
        }
     }
  }
  int mx = 1, idx = 0;
  for (int i = 0; i < n; i++) {
     if (dp[i] > mx) {
        mx = dp[i];
        idx = i;
     }
  }
  cout << mx << "\n";
  vector<int> seq;
  while (true) {
     seq.pb(v[idx]);
     if (par[idx] == idx) break;
     idx = par[idx];
  }
  reverse(seq.begin(), seq.end());
  for (int i = 0; i < mx; i++) {
     cout << seq[i] << " ";
  }
}

維護一個父數組並從 LIS 以父結束父的索引向后,直到到達父 [index] = 索引的索引。

int lis( int *arr, int n )
{
   int *lis, i, j, max = 0, max_index = 0;
   int *print = (int*)malloc(sizeof(int)*n);
   lis = (int*) malloc ( sizeof( int ) * n );
   for ( i = 0; i < n; i++ ){
      lis[i] = 1;
        print[i] = -1
    }
   for ( i = 1; i < n; i++ )
      for ( j = 0; j < i; j++ )
         if ( arr[i] > arr[j] && lis[i] < lis[j] + 1){
            lis[i] = lis[j] + 1;
            print[i] = j;
        }
   for ( i = 0; i < n; i++ ){
      if ( max < lis[i] ){
         max = lis[i];
        max_index = i;
      }
    }
    while(max_index >=0){
        printf("%d ",lis[max_inc_index]);
        max_index = print[max_index];
    }
   /* Free memory to avoid memory leak */
   free( lis );

   return max;
}

使用一個額外的數組來跟蹤索引,索引是最長子序列的一部分,然后遍歷數組以打印所有相應的元素。

動態數組可以聲明為長度等於遞增序列的最大長度。 數組 ANS 將保持最長的遞增序列。

int *ans=(int*)malloc(sizeof(int)*max);

臨時變量用於保留數組中最大長度的索引。

    int index;
    int length; //used to fill array ANS in reverse order.
    for ( i = 0; i < n; i++ )
      {
          if ( max < lis[i] )
          {
              max = lis[i];
              index=i;
          }
      }
    length=max;
    ans[length-1]=arr[index];  //filling array from the last
                               //last element will be the greatest element
    length--;
    while(index>0)
    {
        for(i=index-1;i>=0;i--)
        {
            if(lis[i]+1==lis[index] && arr[i]<arr[index])
            {
                ans[length-1]=arr[i]; 
                index=i;
                length--;
                break;
            }
        }
    }
    for(i=0;i<max;i++)
    {
        printf("%d",ans[i]);
    }

這里的復雜度是 O(n) 而不是 O(n2),即使它可能使用兩個循環,因為每當進入 if 塊時,我們都會將索引值更改為 i。

不是最好的方法,但你可以試試...

int lis(int ar[], int n) {

int max = INT_MIN;
int* lis = new int[n];
int* sub_arr = new int[n];

for (int i = 0; i < n; ++i)
    lis[i] = 1;

for (int i = 1; i < n; ++i) {
    for (int j = 0; j < n; ++j) {
        if(ar[i] > ar[j] && lis[j] + 1 >= lis[i]) {
            lis[i] = lis[j] + 1;
            sub_arr[i] = j;
        }
    }
}

for (int i = 0; i < n; ++i) {
    if(max < lis[i])
        max = ar[i];
}

int k = 0;
stack <int> st;
for (int i = 0; i < n; ++i) {
    if(max == lis[i])
        k = i;
}

cout << "Longest Incresing Subsequence : ";

st.push(k);
while(k > 0) {
    st.push(sub_arr[k]);
    k = sub_arr[k];
}

while (!st.empty()) {
    cout << ar[st.top()] << ' ';
    st.pop();
}
cout << endl;

return max;
}

如果有人對Java版本感興趣。 評論了解釋。

   public int lengthOfLIS(int[] nums) {
    if(nums.length == 0) return 0;
    // array to store sub-problem solution. L[i] stores the length
    // of the longest increasing sub-sequence ends with nums[i]
    int[] L = new int[nums.length];
    // used to print the actual LIS
    int[] P = new int[nums.length];

    // longest increasing sub-sequence having just one element has length 1
    Arrays.fill(L, 1);
    Arrays.fill(P, -1);

    // start from second element in the array
    for(int i=1; i<nums.length; i++) {

        // do for each element in sub-array nums[0..i-1]
        for(int j=0; j<i; j++) {
            // find longest increasing sub-sequence that ends with nums[j]
            // where nums[j] is less than the current element nums[i]
            // and it extends the original sub-sequence increasingly
            if(nums[j] < nums[i] && L[i] < L[j]+1) {
                L[i] = L[j] + 1;
                // store what index helped to extend L[i] 
                P[i] = j;
            }
        }
    }
     /* find the maximum LIS from L calculated also its index */
    int max=L[0], maxIndex=0;
    for(int i=1; i<nums.length; i++) {
        if(max<L[i]) {
            max=L[i];
            maxIndex=i;
        }
    }
    //starting from index of max-length LIS traverse back 
    //using P array populated earlier
    while (maxIndex >= 0) {
        System.out.print(nums[maxIndex]+", ");
        maxIndex = P[maxIndex];
    }
    return max;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM