題目:編程
查找斐波納契數列中第 N 個數。性能
所謂的斐波納契數列是指:編碼
斐波納契數列的前10個數字是:spa
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
code
The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.blog
樣例遞歸
給定 1
,返回 0
內存
給定 2
,返回 1
ci
給定 10
,返回 34
it
編碼:【推薦方式三】
方式一:編程好理解,但代碼複雜,性能較差,且佔用內存;LintCode耗時2475ms
1 public class Solution { 2 /* 3 * @param : an integer 4 * @return: an ineger f(n) 5 */ 6 public int fibonacci(int n) { 7 // write your code here 8 int[] a = null ; 9 10 if(n>2){ 11 a = new int[n]; 12 a[0] = 0; a[1] = 1 ; 13 for(int i=2;i<n;i++){ 14 a[i] = (a[i-1]+a[i-2]); 15 } 16 return a[n-1]; 17 }else if(n==1){ 18 return 0; 19 }else if(n==2){ 20 return 1; 21 } 22 return 0; 23 } 24 }
方式二:遞歸,代碼量小,但耗時更大,LintCode耗時4526ms
1 public class Solution { 2 /* 3 * @param : an integer 4 * @return: an ineger f(n) 5 */ 6 public int fibonacci(int n) { 7 // write your code here 8 if(n==1){ 9 return 0; 10 }else if(n==2){ 11 return 1 ; 12 }else if(n>2){ 13 return (fibonacci(n-1) + fibonacci(n-2)); 14 } 15 return -1; 16 } 17 }
方式三:將遞歸改爲for循環,用兩個變量來存放前兩個數,用c來存放結果;LintCode耗時最短2170ms;
1 public class Solution { 2 /* 3 * @param : an integer 4 * @return: an ineger f(n) 5 */ 6 public int fibonacci(int n) { 7 // write your code here 8 if(n==1){ 9 return 0; 10 }else if(n==2){ 11 return 1 ; 12 }else{ 13 int a=0; 14 int b=1; 15 int c=0; 16 for(int i=3;i<n+1;i++){ 17 c = a+b; 18 a=b; //注意先把b賦值給a,在把計算獲得的c賦值給b 19 b=c; 20 } 21 return c; 22 } 23 } 24 }