Fork me on GitHub

climbing-stairs

/**
*
* @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);
    }
}

这两道题目都有一个特点。 前面的两个数字相加等于紧跟后面的那个数字。 a[i] = a[i-1] + a[i-2];  

 斐波那契数列: https://baike.baidu.com/item/%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B0%E5%88%97/99145?fr=aladdin

posted @ 2019-07-30 17:49  gentleKay  阅读(347)  评论(0编辑  收藏  举报