题解 | #跳台阶#
跳台阶
https://www.nowcoder.com/practice/8c82a5b80378478f9484d87d1c5f12a4
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param number int整型 * @return int整型 */ public int jumpFloor (int number) { // write code here int n1 = 1; int n2 = 2; int nn = 0; for (int i = 2; i <number; i++) { nn = n1 + n2; n1 = n2; n2 = nn; } if (number <= 2)return number; else return nn; } }
当 n = 1 时,只有一种跳法:
当 n = 2 时,有两种跳法:
跳 n 阶台阶,可以先跳 1 阶台阶,再跳 n-1 阶台阶;或者先跳 2 阶台阶,再跳 n-2 阶台阶。而 n-1 和 n-2 阶台阶的跳法可以看成子问题,该问题的递推公式为: