publicintclimbStairs(int n){// 计算根号5的值,因为斐波那契数列的通项公式中涉及到根号5 double sqrt5 =Math.sqrt(5);// 使用斐波那契数列的通项公式来计算第n项的值 double finb =Math.pow((1+ sqrt5)/2, n +1)-Math.pow((1- sqrt5)/2, n +1);// 因为fibn是一个double类型的值,但我们需要一个整数结果,故强转return(int)Math.round(finb / sqrt5);}
我还看到一个好玩儿的解法,给大家看看:
intclimbStairs(int n){int result =0;switch(n){case1: result =1;break;case2: result =2;break;case3: result =3;break;case4: result =5;break;case5: result =8;break;case6: result =13;break;case7: result =21;break;case8: result =34;break;case9: result =55;break;case10: result =89;break;case11: result =144;break;case12: result =233;break;case13: result =377;break;case14: result =610;break;case15: result =987;break;case16: result =1597;break;case17: result =2584;break;case18: result =4181;break;case19: result =6765;break;case20: result =10946;break;case21: result =17711;break;case22: result =28657;break;case23: result =46368;break;case24: result =75025;break;case25: result =121393;break;case26: result =196418;break;case27: result =317811;break;case28: result =514229;break;case29: result =832040;break;case30: result =1346269;break;case31: result =2178309;break;case32: result =3524578;break;case33: result =5702887;break;case34: result =9227465;break;case35: result =14930352;break;case36: result =24157817;break;case37: result =39088169;break;case38: result =63245986;break;case39: result =102334155;break;case40: result =165580141;break;case41: result =267914296;break;case42: result =433494437;break;case43: result =701408733;break;case44: result =1134903170;break;case45: result =1836311903;break;}return result;}