LeetCode(70)-Climbing Stairs

版权声明:XiangYida https://blog.csdn.net/qq_36781505/article/details/83722413

70-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 step + 1 step
2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1 step + 1 step + 1 step
1 step + 2 steps
2 steps + 1 step

题目的意思是爬楼梯,每次爬的时候可以选择爬2阶或者一阶,然后给你n阶台阶,问你有多少种爬上去的可能

嗯?这个题没有找到思路还真的不好做,典型的动态规划(嗯,虽然还没搞懂动态规划)
怎么说呢,找出局部能替代整体的部分,相当于递推吧。

比如这个题,你要爬到第i阶,那么有两种可能,第一种你是从i-1阶跳一阶跳上来的,第二种,你是从i-2阶跳2阶跳上来的,所以第i阶的种数=(i-1)的种数+(i-2)的种数,然后代码就是这样了,也就几行。(好懒,好几天没做题了)

public int climbStairs(int n) {
       int a1=1;
       int a2=2;
       int a3=0;
       if(n==1||n==2)return n;
       for(int i=3;i<=n;i++){
           a3=a2+a1;
           a1=a2;
           a2=a3;
       }
       return a3;
   }

猜你喜欢

转载自blog.csdn.net/qq_36781505/article/details/83722413
今日推荐