题解 | 跳台阶
跳台阶
https://www.nowcoder.com/practice/8c82a5b80378478f9484d87d1c5f12a4
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param number int整型 * @return int整型 */ /** result = first + second; :根据递推公式 f(n) = f(n - 1) + f(n - 2),计算当前第 i 级台阶的跳法数量。这里 first 相当于 f(n - 2),second 相当于 f(n - 1),所以 result 就是 f(n)。 first = second; :更新 first 的值为 second。在计算下一个台阶(第 i + 1 级)的跳法数量时,原来的 f(n - 1) 就变成了新的 f(n - 2),所以把 second 的值赋给 first。 second = result; :更新 second 的值为 result。同理,原来的 f(n) 变成了新的 f(n - 1),所以把 result 的值赋给 second。 */ public int jumpFloor (int number) { if(number<=2){ return number; } int first = 1; int second = 2; int result = 0; for(int i = 3;i<=number;i++){ result = first + second; first = second; second = result; } return result; // write code here } }
递归和动态规划解法
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param number int整型 * @return int整型 */ /** result = first + second; :根据递推公式 f(n) = f(n - 1) + f(n - 2),计算当前第 i 级台阶的跳法数量。这里 first 相当于 f(n - 2),second 相当于 f(n - 1),所以 result 就是 f(n)。 first = second; :更新 first 的值为 second。在计算下一个台阶(第 i + 1 级)的跳法数量时,原来的 f(n - 1) 就变成了新的 f(n - 2),所以把 second 的值赋给 first。 second = result; :更新 second 的值为 result。同理,原来的 f(n) 变成了新的 f(n - 1),所以把 result 的值赋给 second。 */ public int jumpFloor (int number) { if(number<=2){ return number; } int first = 1; int second = 2; int result = 0; for(int i = 3;i<=number;i++){ result = first + second; first = second; second = result; } return result; // write code here } }