編程之美 求數組中的最長遞增子序列

來源:互聯網
上載者:User

如題,例如:存在數組 1,-1,2,-3,4,-5,6,-7 ,則最長的遞增子序列是:1,2,4,6.

法一:

        蠻力法

        

[html]
view plaincopyprint?
  1. int Lis(int* arr,int n)  
  2. {  
  3.     int iCount=0;//記錄子序列的個數  
  4.     int tmp_count=0;  
  5.     int tmp;  
  6.    for(int i=0;i<n-1;i++)  
  7.    {   
  8.           tmp=arr[i];  
  9.            
  10.       for(int j=i+1;j<n-1;j++)  
  11.       {  
  12.             
  13.             
  14.           if(arr[j]>tmp)   
  15.             {  
  16.               iCount++;  
  17.               tmp=arr[j];  
  18.           }  
  19.       }  
  20.         if(iCount>tmp_count)  
  21.           {  
  22.             tmp_count=iCount;  
  23.               
  24.           }  
  25.         iCount=0;  
  26.    }  
  27.    
  28. return tmp_count+1;  
  29. }  

複雜度為O(N^2);

法二:

         利用DP來做,最有問題,一般都用dp來做,關鍵是找到遞迴公式。

用LIS[i]記錄位置i處,最長的遞增子序列,編程之美上的解法,真心看不懂,記錄下來,以後再看:

[cpp]
view plaincopyprint?
  1. int LIS(int[] array)  
  2.        {   
  3.          int[] LIS=new int[array.Length];  
  4.          for (int i = 0; i < array.Length; i++)  
  5.          {  
  6.              LIS[i] = 1;  
  7.              for (int j = 0; j < i; j++)  
  8.              {  
  9.                  if (array[i] > array[j] && LIS[j] + 1 > LIS[i])  
  10.                      LIS[i] = LIS[j] + 1;  
  11.              }  
  12.            
  13.          }  
  14.          
  15.          
  16.        }  
  17.        return Max(LIS);  
  18.    }  

法三:先對數組排序,然後找出原數組和排序後數組的LCS,就是我們要找的最長遞增子序列。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.