第十一周:70. Climbing Stairs

    xiaoxiao2021-03-25  68

    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.

    Subscribe to see which companies asked this question.

    我把前五项列出来,假如n=1那么有1种方法;假如n=2,那么有2种方法;假如n=3,那么有3种方法;假如n=4,那么有5种方法;假如n=5,那么有8种方法...这样列下去发觉这是一个斐波那契数列,用递归完成。

    发现当用递归完成之后,会超时。

    于是上网看了一下什么情况,原来发现递归解决这道题会出现超时错误,于是只能一步一步做出来。

    Accepted Code:

    int climbStairs(int n) { if(n == 0 || n == 1) return 1; int res = 0; int a = 1; int b = 1; for(int i = 2; i <= n; i ++) { res = a + b; a = b; b = res; } return res; }

    转载请注明原文地址: https://ju.6miu.com/read-32878.html

    最新回复(0)