Climping Stairs lintcode/leetcode

本文探讨了一个经典的编程面试题——爬楼梯问题,并通过递归、动态规划等方法解决该问题,最终转化为斐波那契数列求解。

    public int climbStairs(int n) {
        // write your code here
        if( n== 0)return 1;
	if (n < 3)
		return n;
	int n1 = 1;
	int n2 = 2;
	for (int i = 3; i <= n; i+=2)
	{
		n1 = n1 + n2;
		n2 = n1 + n2;//二步长求斐波那契
	}
	if (n%2 == 1)return n1;
	return n2;
}


Climbing Stairs

    

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?

简单题目,相当于fibonacci数列问题,难点就是要会思维转换,转换成为递归求解问题,多训练就可以了。

所以这种类型的题目相对于没有形成递归逻辑思维的人来说,应该算是难题。

我的想法是:

每次有两种选择,两种选择之后又是各有两种选择,如此循环,正好是递归求解的问题。

写成递归程序其实非常简单,三个语句就可以:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int climbStairsRecur(int n) {  
  2.         if (n == 1) return 1;  
  3.         if (n == 2) return 2;  
  4.         return climbStairsRecur(n-1) + climbStairsRecur(n-2);  
  5.     }  

但是递归程序一般都是太慢了,因为像Fibonacci问题一样,重复计算了很多分支,我们使用动态规划法填表,提高效率,程序也很简单,如下:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int climbStairs(int n)  
  2.     {  
  3.         vector<int> res(n+1);  
  4.         res[0] = 1;  
  5.         res[1] = 1;  
  6.         for (int i = 2; i <= n; i++)  
  7.         {  
  8.             res[i] = res[i-1] + res[i-2];  
  9.         }  
  10.         return res[n];  
  11.     }  

动态规划法用熟了,高手就需要节省空间了,如下:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int climbStairs2(int n)  
  2.     {  
  3.         vector<int> res(3);  
  4.         res[0] = 1;  
  5.         res[1] = 1;  
  6.         for (int i = 2; i <= n; i++)  
  7.         {  
  8.             res[i%3] = res[(i-1)%3] + res[(i-2)%3];  
  9.         }  
  10.         return res[n%3];  
  11.     }  

当然,不使用上面的数组也是可以的,直接使用三个变量保存结果也是一样的。

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //2014-2-10 update  
  2.     int climbStairs(int n)  
  3.     {  
  4.         if (n < 4) return n;  
  5.         int a = 2, b = 3, c = 5;  
  6.         for (int i = 5; i <= n; i++)  
  7.         {  
  8.             a = c;  
  9.             c = b+c;  
  10.             b = a;  
  11.         }  
  12.         return c;  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值