LeetCode之“动态规划”:Climbing Stairs
2015-06-09 17:07
441 查看
题目链接
题目要求
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?
做这道题容易陷入的思维就是:所有step加起来的总和是n。俺这种思维去解决这个问题的话会显得很复杂。
按动态规划的思维,要爬到第n阶,可以从第n-1阶爬1阶到达,也可以从第n-2阶爬2阶到达,因此爬到第n阶的方法有这么多种:
按此思维的程序代码如下:
题目要求
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?
做这道题容易陷入的思维就是:所有step加起来的总和是n。俺这种思维去解决这个问题的话会显得很复杂。
按动态规划的思维,要爬到第n阶,可以从第n-1阶爬1阶到达,也可以从第n-2阶爬2阶到达,因此爬到第n阶的方法有这么多种:
dp[n] = dp[n - 1] + dp[n - 2]
按此思维的程序代码如下:
class Solution { public: int climbStairs(int n) { if(n == 0 || n == 1 || n == 2) return n; int * dp = new int[n + 1]; dp[0] = 0; dp[1] = 1; dp[2] = 2; for(int i = 3; i < n + 1; i++) dp[i] = dp[i - 1] + dp[i - 2]; return dp ; } };
相关文章推荐
- org.tinygroup.beancontainer-IOC、AOP框架
- POJ1995 Raising Modulo Numbers 快速幂取模
- 使用Genymotion调试出现错误INSTALL_FAILED_CPU_ABI_INCOMPATI
- HCE AID选择策略测试
- http://blog.csdn.net/lenotang/article/details/2823230
- leetcode_Factorial Trailing Zeroes_easy
- Leetcode[219]-Contains Duplicate II
- 水题 Codeforces Beta Round #70 (Div. 2) A. Haiku
- sleep() 和 wait() 有什么区别?
- MacBook Air 使用技巧
- Genymotion首次运行程序出现错误Installation error: INSTALL_FAILED_CPU_ABI_INCOMPATIBLE
- sctp AIX
- Contains Duplicate III 重复数 堆实现
- Contains Duplicate II 重复数HASH
- Mesos单点Master集群部署和High Availability集群部署
- [Selenium]重写拖拽dragWidgetToElementContainner()
- 在main()之前,IAR都做了啥?
- mail.rc配置外网发邮件
- POJ 1422 Air Raid (二分图最小点集覆盖 匈牙利算法)
- Container With Most Water :