【Climbing Stairs】cpp
题目:
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?
代码:
class Solution { public: int climbStairs(int n) { int prev = 0; int curr = 1; for (int i = 0; i<n; ++i) { const int tmp = curr; curr = curr + prev; prev = tmp; } return curr; } };
Tips:
1. 这道题可以抽象成求Fibonacci数列的通项(只看最后一步:从n-1到n迈一个台阶;从n-2到n迈两个台阶)
==================================================
第二次过这道题,没有想到直接用斐波那契数列的思想。
首先想到的做法是直接递归,结果超时;后来想到可以用一个记忆hashmap,保存计算过的中间结果,于是有了下面0msAC的代码。
class Solution { public: int climbStairs(int n) { map<int, int> calculated; calculated[0] = 1; calculated[1] = 1; return Solution::subStairs(n, calculated); } static int subStairs(int n, map<int, int>& calculated) { if ( n==0 ) return 0; if ( n==1 ) return 1; int way1 = calculated.find(n-1)!=calculated.end() ? calculated[n-1] : calculated[n-1]=Solution::subStairs(n-1, calculated); int way2 = calculated.find(n-2)!=calculated.end() ? calculated[n-2] : calculated[n-2]=Solution::subStairs(n-2, calculated); return way1+way2; } };
tips:
这个思路还是非常通用的。
原来斐波那契数列思路的非递归实现也要记住,这段代码也很漂亮。