/**
*
* @author gentleKay
* You are climbing a stair case. It takes n steps to reach to the top.
* Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
*
* 你在爬楼梯。它需要N个步骤才能到达顶部。
* 每次你可以爬1到2步。你能用多少种不同的方式爬到顶峰?
*/
这是一题动态规划的题目,可以和这道题一起来看:
https://www.cnblogs.com/strive-19970713/p/11262614.html
方法一:(动态规划 空间和时间复杂度都为O(n))
/** * * @author gentleKay * You are climbing a stair case. It takes n steps to reach to the top. * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? * * 你在爬楼梯。它需要N个步骤才能到达顶部。 * 每次你可以爬1到2步。你能用多少种不同的方式爬到顶峰? */ public class Main22 { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(Main22.climbStairs(1)); } public static int climbStairs(int n) { int[] a = new int[n+1]; a[0] = 1; a[1] = 1; for (int i=2;i<a.length;i++) { a[i] = a[i-1] + a[i-2]; } return a[n]; } }
方法二:(递归 在letcode会超时错误)
/** * * @author gentleKay * You are climbing a stair case. It takes n steps to reach to the top. * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? * * 你在爬楼梯。它需要N个步骤才能到达顶部。 * 每次你可以爬1到2步。你能用多少种不同的方式爬到顶峰? */ public class Main22 { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(Main22.climbStairs(1)); } public static int climbStairs(int n) { if (n == 1) { return 1; } if (n == 2) { return 2; } return climbStairs(n-1) + climbStairs(n-2); } }