Climbing Stairs
生活随笔
收集整理的這篇文章主要介紹了
Climbing Stairs
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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?
?
分析:考慮走第n步時(shí)的情況,可以從第n-1個(gè)臺(tái)階走一步,也可以從第n-2個(gè)臺(tái)階走兩步。即f(n) = f(n-1) + f(n-2),同時(shí)f(1) = 1, f(2) = 2.
?
1. 使用遞歸,結(jié)果超時(shí)了。
class Solution { public:int climbStairs(int n) {if(n == 1) return 1;if(n == 2) return 2;else return(climbStairs(n-1) + climbStairs(n-2));} }; View Code2. 和斐波那契亞數(shù)列差不多,于是用了for循環(huán)來(lái)代替,2ms。
1 class Solution { 2 public: 3 int climbStairs(int n) { 4 if(n <= 2) return n; 5 6 int *result = new int[n]; 7 result[0] = 1; 8 result[1] = 2; 9 for(int i = 2; i < n; i++) 10 result[i] = result[i-1] + result[i-2]; 11 12 return result[n-1]; 13 } 14 };轉(zhuǎn)載于:https://www.cnblogs.com/amazingzoe/p/4442650.html
總結(jié)
以上是生活随笔為你收集整理的Climbing Stairs的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 最全英文停用词表整理(891个)
- 下一篇: 【FLUENT案例】04:利用DDPM+