Leetcode70 Climbing Stairs

问题描述

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?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

中文题意

爬n阶的楼梯,每次只能爬1阶或者2阶,求有几种爬阶方式。


方法一

(1)如果n=1,那么只能一次一阶,有一种方式;

(2)如果n=2,那么可以一次一阶,两次到达顶端;或者是一次2阶,共两种方式;

(3)在其他情况中,Step(i)表示到第i阶的方法总数,那么i,i-1,i-2之间的关系为:Step(i)=Step(i-1)+Step(i-2)。(自底向上和自上向下都满足)。

class Solution {
  
    public int climbStairs(int n) {
      
        if(n <= 2){
            return n;
        }
        
        int num1 = 1;
        int num2 = 2;
        int num = 0;
        
        for(int i = 3; i <n+1;i++){
            num = num1 + num2;
            
            num1 = num2;
            num2 = num;
        }
        
        return num;
    }
    
  
    
}


方法二

使用数学中的排列组合

总阶数为n,那么一次2阶出现的最多情况为i=n/2。那么一次1阶出现的总数为n-2i,总的步数为i+n-2i=n-i。使用组合的概念,就相当于从总次数(n-i)中抽取i次的组合数。

class Solution {
  
    public int climbStairs(int n) {
     
        double i = n/2;//i表示一步2阶出现的最高次数
        double sum = 1;//记录方法数
        
        for(int l = 1;l < i+1;l++){//某次一步2阶出现l次
            double temp = n-l;
            for(int k = 1; k < l;k++){//计算组合公式中的分子,即(n-l)*(n-l-1)*...*(n-l-l+1)
                temp = temp * (n-l-k);
            }
            
            for(int m = l;m > 0;m--){//计算组合公式中的分母,即l*(l-1)*(l-2)*...*1
                temp /= m;
            }
            
            sum += temp;
        }
         return (int)sum;
    }
    
   
}

tips:在方法二中,使用了double类型的变量,是因为for循环中使用有/的运算,如果使用int后,那么偏差会越来越大。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值