1 Packageinterview;2 //There is a Fibonacci sequence function, the first k number is 1, and no one behind is the sum of the former K-bit, for example, k=4, the function3 //The function returns a value of 1,1,1,1,4,7,13,25,494 Public classRecursiveoptimize {5 Static intFib_k (intNintk) {6 if(n<k)7 return1;8 intresult = 0;9 for(inti=0;i<k;i++){TenResult + = Fib_k (n-i-1, k); One } A returnresult; - } - Static intFib_k_optimize (intNintk) { the if(n<k) - return1; - int[] fib =New int[N+1]; - for(inti=0;i<k;i++){ +Fib[i]=1; - } + for(inti=k;i<=n;i++) { A intresult = 0; at for(intj=0;j<k;j++){ -Result + = Fib[i-j-1]; - } -fib[i]=result; - } - returnFib[n]; in } - Public Static voidMain (string[] args) { to LongStart =system.nanotime (); + for(inti=0;i<20;i++){ -System.out.print (Fib_k (i,4) + ""); the } * LongEnd =system.nanotime (); $System.out.println ("\ n" + (end-start));Panax Notoginseng - //=================================== theStart =system.nanotime (); + for(inti=0;i<20;i++){ ASystem.out.print (Fib_k_optimize (i,4) + ""); the } +End =system.nanotime (); -System.out.println ("\ n" + (end-start)); $ } $ -}
Recursive algorithm and optimization