LeetCode之Climbing Stairs与斐波那契数列的联想
2016-01-03 21:56
369 查看
题目:
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?
看到题目之后,毫不犹豫想出公式:f(n)=f(n-1)+f(n-2),明显用动态规划算法,而且巧合的是,这公式跟斐波那契数列一模一样,只是初始值不一样而已。然而,当我用dp做完提交时,不好意思超时了,心中一万只草泥马跑过啊,一道easy的题目竟然超时。。。那好,竟然用dp不行,那就用分治法呗,我们可以把楼梯砍一半,爬一半的方法数*另一半的方法数是不是就等于最终答案呢,不止,还少算了如果在这两半楼梯的联接处正好走两步时的情况,好了,我们终于思路明确了,代码如下所示:
class Solution {
public:
int climbStairs(int n) {
if (n <= 3)
return n;
else {
int leftCount = climbStairs(n / 2);
int rightCount = leftCount;
int tmp = climbStairs(n / 2 - 1);
int tmp2 = tmp;
if (n % 2) {
rightCount = tmp + leftCount;
tmp2 = leftCount;
}
return leftCount*rightCount + tmp*tmp2;
}
}
};
虽然这题是一道easy题,但他促进了我的思考,而且和斐波那契数列如此的巧合,细想一下,如果题目一开始就让我们实现斐波那契数列,恐怕怎么也想不出用分治法吧,至少对于我来说是这样的。希望对大家也有所帮助。
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?
看到题目之后,毫不犹豫想出公式:f(n)=f(n-1)+f(n-2),明显用动态规划算法,而且巧合的是,这公式跟斐波那契数列一模一样,只是初始值不一样而已。然而,当我用dp做完提交时,不好意思超时了,心中一万只草泥马跑过啊,一道easy的题目竟然超时。。。那好,竟然用dp不行,那就用分治法呗,我们可以把楼梯砍一半,爬一半的方法数*另一半的方法数是不是就等于最终答案呢,不止,还少算了如果在这两半楼梯的联接处正好走两步时的情况,好了,我们终于思路明确了,代码如下所示:
class Solution {
public:
int climbStairs(int n) {
if (n <= 3)
return n;
else {
int leftCount = climbStairs(n / 2);
int rightCount = leftCount;
int tmp = climbStairs(n / 2 - 1);
int tmp2 = tmp;
if (n % 2) {
rightCount = tmp + leftCount;
tmp2 = leftCount;
}
return leftCount*rightCount + tmp*tmp2;
}
}
};
虽然这题是一道easy题,但他促进了我的思考,而且和斐波那契数列如此的巧合,细想一下,如果题目一开始就让我们实现斐波那契数列,恐怕怎么也想不出用分治法吧,至少对于我来说是这样的。希望对大家也有所帮助。
相关文章推荐
- KMP字符串模式匹配详解http://blog.csdn.net/lin_bei/article/details/1252686
- Develop--Training(六)Getting Started--Working with System Permissions
- POJ 2135 Farm Tour && HDU 2686 Matrix && HDU 3376 Matrix Again 费用流求来回最短路
- 彻底解决INSTALL_FAILED_UPDATE_INCOMPATIBLE的安装错误
- Installation error: INSTALL_FAILED_NO_MATCHING_ABIS
- RAID原理以及分类
- org.hibernate.AssertionFailure: null id in entry (don't flush the Session after an exception occurs)
- 理解cookie的path和domain属性
- 被误传的Cookie的Domain属性
- [leetcode] 11. Container With Most Water 解题报告
- no copy constructor available or copy constructor is declared 'explicit'
- Convolutional Neural Networks at Constrained Time Cost(精读)
- 人工智能节目主持人诞生
- 散列冲突处理 http://www.nowamagic.net/academy/detail/3008050
- UVA1450-Airport
- HDU 5009 Paint Pearls (动态规划)
- 第六届福建省大学生程序设计竞赛 Problem E The Longest Straight
- traincascade与AdaBoost的opencv实现框架
- 151217MainTest主函数详细介绍
- RAID技术学习小结