类似斐波那契数列的思想,若所求方法表示为f(n),因为当台阶大于3时,可看做是 f(n)=f(n-1)+f(n-2)+f(n-3);//因为踏入最后一节阶梯有三种方法,最后一步是一步,两步,三步。 代码如下: public static void main(String[] args) { int f1 = 1; int f2 = 2; int f3 = 4; int result = 0; for(int i = 4;i<=15;i++){ result = f1+f2+f3; f1 = f2; f2 = f3; f3 = result; } System.out.println(result); }
def cnt(n): dic = {1: 1, 2: 2, 3: 4} if n <= 3: return dic[n] return cnt(n-1) + cnt(n-2) + cnt(n-3) print cnt(15)
}
/* * 解题思想:设总走法为f(n),第一步有三种走法:走一步、走两步、走三步, * 走一步后剩余走法为 f(n-1),走两步剩余走法为f(n-2).... * 所以可以得到f(n) = f(n-1) + f(n-2) + f(n-3),然后就可以用递归或者迭代实现 */
function methods(n) { if (n === 1) return 1; if (n === 2) return 2; if (n === 3) return 4; return methods(n-1) + methods(n-2) + methods(n-3) }
function methods2(n, x = 1, y = 2, z = 4) { if (n <= 1) return x; if (n <= 2) return y; if (n <= 3) return z; return methods2(n - 1, y, z, x + y + z) }
function methods3(n) { let [x, y, z] = [1, 2, 4]; if (n === 1) return x; if (n === 2) return y; if (n === 3) return z; for (let i = 4; i <= n; i ++) { [x, y, z] = [y, z, x + y + z]; } return z; } console.log(methods3(15))
int step(int totalStep) {int *steps = new int[totalStep + 1]; steps[1] = 1; steps[2] = 2; steps[3] = 4; for (int i = 4; i <= totalStep; i++) { steps[i] = steps[i - 3] + steps[i - 2] + steps[i - 1]; } int result = steps[totalStep]; delete[] steps; return steps[totalStep]; }