letecode [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. 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阶楼梯,可一次爬一阶或两阶,求共多少种爬法。
理 解 :
n=0时,爬法=0;n=1时,爬法=1;n=2时,可爬2两次一阶、或一次两阶,爬法=2;
从n=3开始,设爬法为f,则f(n) = f(n-1) + f(n-2);表示n阶阶梯的爬法等于当前爬一阶的种类+当前爬两阶的种类。
代 码 C++:
class Solution { public: int climbStairs(int n) { int *arr = new int[n+1]; if(n==1 || n==2) return n; arr[0] = 0; arr[1] = 1; arr[2] = 2; int i; for(i=3;i<=n;++i){ arr[i] = arr[i-1] + arr[i-2]; } return arr[n]; } };
运行结果:
执行用时 : 4 ms 内存消耗 : 8.5 MB
标签:arr,int,top,step,steps,70,Climbing,climb,Stairs 来源: https://www.cnblogs.com/lpomeloz/p/10983623.html