跳台阶+变态跳台阶(java)

xiaoxiao2021-02-28  48

我GitHub上的:剑指offer题解​​​​​​​

跳台阶

题目描述:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。并分析算法的时间复杂度

分析:若跳n级台阶,第一次可以跳1级,剩下就是f(n-1);第一次可以跳2级,剩下就是f(n-2)。所以f(n)=f(n-1)+f(n-2)。其中f(0)=0;f(1)=1;f(2)=2。这就是一个Fibonacci数列。虽然不是完全一样,前两项变成了 1 2了

 

递归实现:

public int jumpFloor(int target) { if (target < 0) { return 0; } if (target == 0 ||target == 1) { return 1; } return 2*jumpFloor(target-1); }

这是一个最低级的实现,时间复杂度度为O(2^n)。如果n很大,数据类型应改为long

 

非递归实现:

public int jumpFloor(int target) { if (target <= 0) { return 0; } if (target == 1) { return 1; } if (target == 2) { return 2; } int currOne = 1; int currTwo = 2; int result = 0; for (int i = 3; i <= target; i++) { result = currOne + currTwo; currOne = currTwo; currTwo = result; } return result; }

 

 

 

时间复杂度:O(n);空间复杂度:O(1)  

 

变态跳台阶

题目描述:一只青蛙一次可以跳上1级台阶,也可以跳上2级……也可以跳n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。并分析算法的时间复杂度

分析:第一步有n种跳法:跳1级跳2级……跳n级

跳1级,剩下跳法是f(n-1)

跳2级,剩下跳法是f(n-2)

跳3级,剩下跳法是f(n-3)

……………………………………

跳n-1级,剩下跳法是f(1)

跳n级,剩下跳法是f(0),故为1(表示直接跳n级一步到位)

所以f(n)=f(n-1)+f(n-2)+……+f(1)+f(0)

说明:根据以上分析可得

 

当n=0时,虽然应为0,但是考虑计算方便,我们设f(0)=1当n=1时,只有一种方法,f(1)=1当n=2时,会有两种方式,一次1级或者直接2级,f(2)=f(2-1)+f(2-2)当n=3时,会有三种方式,第一次跳1级,剩下就是f(3-1);第一次跳2级,剩下f(3-2);第一次直接三级,那么就剩下f(3-3)=1(这也是为啥设f(0)=1的原因);f(3)=3当n=n时,会有n种方式, f(n) = f(n-1)+f(n-2)+...+f(n-(n-1)) + f(n-n) => f(0) + f(1) + f(2) + f(3) + ... + f(n-1)简化:f(n)=f(n-1)+f(n-2)+……+f(1)+f(0)      f(n-1)=f(n-2)+f(n-3)+……+f(1)+f(0)  所以f(n)=2*f(n-1)最终结论:

            | 1       ,(n=0 ) 

f(n) =   | 1       ,(n=1 )

            | 2*f(n-1),(n>=2)

递归实现

public static int jumpFloor(int target) { if (target < 0) { return 0; } if (target == 0 ||target == 1) { return 1; } return 2*jumpFloor(target-1); }

非递归实现

public static int jumpFloor(int target) { if (target < 0) { return 0; } if (target == 0 ||target == 1) { return 1; } int fn = 1; for(int i = 2;i <= target; i++){ fn = 2 * fn; } return fn; }

另解:移位

public static int jumpFloor(int target) { return 1<<--target; }
转载请注明原文地址: https://www.6miu.com/read-2624228.html

最新回复(0)