zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    下载安装安卓开发工具
    斐波那契数列
    各位相加
    求连续最大子序列和
    反转字符串中的单词
    统计位数为偶数的数字
    Express框架的整体感知
    node.js当中的http模块与url模块的简单介绍
    formidable处理提交的表单或文件的简单介绍
    30分钟,学会经典小游戏编程!
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11271675.html
Copyright © 2011-2022 走看看