之前做遞增子序列編程題的時候就考慮過用遞歸,今天上午寫了一下,感覺用遞歸並沒有什么意義,從最后找到邊界,再從邊界往后一次一次的和前一個比較,比前一個大就讓當前遞增子序列+1,不大就給開始和結束位置重新賦值,並時時更新最長子序列。思路和正常寫完全一樣,無非就是遞歸找到了邊界。(因為比較習慣用下標,所以就沒用地址)
1 #include<stdio.h> 2 #include<stdlib.h> 3 4 #define maxsize 10000 5 6 typedef int Status; 7 8 typedef struct 9 { 10 int start; 11 int end; 12 }SubSeq;//記錄子序列開始位置,結束位置 13 14 void PrintSub(SubSeq Max,int a[]) 15 { 16 for(int i=Max.start;i<Max.end;++i) 17 printf("%d ",a[i-1]); 18 printf("%d",a[Max.end-1]); 19 } 20 21 Status GetSub(int a[],SubSeq &Cur,SubSeq &Max,int n); 22 23 int main() 24 { 25 int n; 26 scanf("%d",&n); 27 int a[maxsize]; 28 for(int i=0;i<n;++i) 29 scanf("%d",&a[i]); 30 31 SubSeq Cur;//當前遞增子序列 32 SubSeq Max;//最長遞增子序列 33 34 GetSub(a,Cur,Max,n); 35 36 PrintSub(Max,a); 37 38 return 0; 39 40 41 } 42 43 Status GetSub(int a[],SubSeq &Cur,SubSeq &Max,int n) 44 { 45 if(n==0) return 0; 46 47 if(n==1)//邊界 48 { 49 Cur.start=1; 50 Cur.end=1; 51 Max.start=1; 52 Max.end=1; 53 } 54 else 55 { 56 GetSub(a,Cur,Max,n-1); 57 58 if(a[n-1]>a[n-2]) 59 Cur.end++; 60 else 61 { 62 Cur.start=n; 63 Cur.end=n;//容易亂 64 } 65 66 if(Cur.end-Cur.start>Max.end-Max.start) 67 { 68 Max.start=Cur.start; 69 Max.end=Cur.end; 70 } 71 72 } 73 74 return 1; 75 }