博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]Climbing Stairs
阅读量:6875 次
发布时间:2019-06-26

本文共 939 字,大约阅读时间需要 3 分钟。

Description:

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?

 

大意:

走台阶,一共有n个台阶。

每次可以走一步或者二步。有几种方法可以到达顶层? 

 

解答:

典型的一维动态规划问题(Dynamic Programming,DP)。

从第0个台阶走到第i个台阶的走法,可以看成一下两种走法的和:

1)从第0个台阶走到第i-1个台阶,再走1步;

2)从第0个台阶走到第i-2个台阶,再走2步;

因此,状态转移方程为:OPT(i) = OPT(i-1) + OPT(i-2)

对于基本情况:OPT(0) = 1; OPT(1) = 1。

 

下面的代码中,使用一维动态数组记录第i步的走法,直到计算出n个台阶的走法为止。

算法的效率为O(n)

 

1 class Solution { 2 public: 3     int climbStairs(int n) { 4          5         if( n <= 0 ) 6         { 7             return 0; 8         } 9         10         int *result = new int[n+1];11         result[0] = 1;12         result[1] = 1;13         14         for( int i = 2; i <= n; i++ )15         {16             result[i] = result[i-1] + result[i-2];17         }18         19         return result[n];20     }21 };

 

转载于:https://www.cnblogs.com/TheLeaf-2010/p/3785881.html

你可能感兴趣的文章
智慧东湖让城市慢游更幸福
查看>>
陕西联通推进高速公路WiFi覆盖
查看>>
Linux之iconv转换文本格式的问题
查看>>
linux 用户权限和组权限
查看>>
RPM的使用
查看>>
我的友情链接
查看>>
lvs
查看>>
原型图设计软件
查看>>
setTimeout和setIntelval的区别
查看>>
[C#]通过方法获得游戏人数和玩家姓名
查看>>
How to rotate a bitmap
查看>>
spring常见注解
查看>>
我的友情链接
查看>>
Linux 磁盘分区
查看>>
基于虚拟用户的邮件服务器在企业网中的应用
查看>>
android开发中shape的绘制
查看>>
在XP系统下安装ubuntu12.04
查看>>
数据库同步过程中一致性和完整性的保证
查看>>
VC++中图像处理类CBitmap的用法
查看>>
c# 建筑者模式的具体实现
查看>>