题目:
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,则step(n) = step(n-1) + step(n-2)。因为对于n-1的情况,只能是再上一阶台阶成为n,而对于n-2的情况,如果走一步,那么久和n-1一样了,因此若要不同就只能走2步直接变成n。
代码:
class Solution { public: int climbStairs(int n) { if (n <= 2) return n; int step = 3, s1 = 1, s2 = 2, tmp; while (step <= n) { tmp = s1 + s2; s1 = s2; s2 = tmp; ++step; } return s2; } };
递归法(在LeetCode上会超时,应该是堆栈大小太大了):
class Solution { public: int climbStairs(int n) { if(n <= 2) return n; return climbStairs(n-1) + climbStairs(n-2); } };