青蛙跳台阶,类似于Fibonacci
跳台阶
http://www.nowcoder.com/questionTerminal/8c82a5b80378478f9484d87d1c5f12a4
public class Solution {
//解法一
public int jumpFloor(int target) {
if( target == 1 || target == 2){
return target;
}
return jumpFloor(target-1) + jumpFloor(target-2);
}
//解法二 public int jumpFloor(int target){ if(target == 1 || target == 2){ return target; } int ans[] = new int[target]; ans[0] = 1; ans[1] = 2; for(int i = 2;i <= target-1;i++){ ans[i] = ans[i-1] + ans[i-2]; } return ans[target - 1]; } //解法三 public int jumpFloor(int target){ if(target == 1 || target == 2){ return target; } int temp = 1; int ans = 2; for(int i = 2;i <= target-1;i++){ ans = ans + temp; temp = ans - temp; } return ans; } //解法四 public int jumpFloor(int target) {//从1开始,target+1;从0开始,target double a = Math.sqrt(5.0); double temp1 = (1.0 + a)/2.0; double temp2 = (1.0 - a)/2.0; return (int)(1.0/a*(Math.pow(temp1, target+1) - Math.pow(temp2, target+1))); }
}