首页 > 代码库 > LeetCode "Climbing Stairs"
LeetCode "Climbing Stairs"
The best way to learn DP from DFS! Nice problem.
My intuition is that it can be solved by DFS:
class Solution {public: int climbStairs(int n) { if (n == 0) return 1; int cnt0 = climbStairs(n - 1); int cnt1 = 0; if(n >= 2) cnt1 = climbStairs(n - 2); return cnt0 + cnt1; }};
You can get correct answer by this, but it is taking too long - TLE.
Actually, the equation is quite obvious in above code: s[n] = s[n-1] + s[n-2] with s[1] = 1; s[2] = 2. Sooooo beautiful:
class Solution {public: int climbStairs(int n) { if (n == 0) return 0; if (n == 1) return 1; if (n == 2) return 2; // S[n] = S[n-1] + S[n-2]; S[1] = 1; S[2] = 2 int ret = 0; int *s = new int[n + 1]; s[1] = 1; s[2] = 2; for (int i = 3; i <= n; i++) { s[i] = s[i - 1] + s[i - 2]; } ret = s[n]; delete[] s; return ret; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。