Climbing Stairs -- leetcode

前端之家收集整理的这篇文章主要介绍了Climbing Stairs -- leetcode前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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?


此题用动太计划解决

递归式为:dp[n] = dp[n⑴] + dp[n⑵]

爬到第n层,有两种途径,1步从n⑴上来,1下跨两步从n⑵上来。

即要求出爬到第n层的所以方法,需知道爬到第n⑴层,n⑵层的方法


关于出发点0层,可以定义为有1种方法,即不动。既不跨1步,也不跨两步,就到达。

比0层更低的,定义为0种办法。

这也可看做是Fibonacci求解。

0,1,2,3,5,8,13,21,34,...


class Solution { public: int climbStairs(int n) { if (n == 0 || n == 1) return 1; int stepOne = 1,stepTwo = 1; int allWays; for (int i=2; i<=n; i++) { allWays = stepOne + stepTwo; stepTwo = stepOne; stepOne = allWays; } return allWays; } };


猜你在找的PHP相关文章