LeetCode 70 Climbing Stairs(爬楼梯)(动态规划)(*)
2016-01-14 07:12
615 查看
翻译
[code]你正在爬一个楼梯。它需要n步才能到底顶部。 每次你可以爬1步或者2两步。 那么你有多少种不同的方法爬到顶部呢?
原文
[code]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?
分析
动态规划基础题,首先设置3个变量用于转换:[code]int dp1 = 1, dp2 = 2, dpWay = 0;
根据题意,一次只能是一步或两步,所以当n等于2时,有两种走法:1+1,2。
[code]if (n <= 1) return dp1; if (n == 2) return dp2;
从3开始,因为可以直接获得它的步数结果,所以直接写成:
[code]while ((n--)-2) { }
最终里面的变化方式为:
[code]dpWay = dp1 + dp2; dp1 = dp2; dp2 = dpWay;
上一篇博客: LeetCode 206 Reverse Linked List(反转链表)(四步将递归改写成迭代)(*) ,介绍了如何将递归改写成迭代,看过的童鞋应该会觉得非常容易的,那么这里再来转换一次:
[code]int climbStairsIter(int n, int dpWay,int dp1, int dp2) { if (n <= 1) return dp1; if (n == 2) return dp2; if ((n--) - 2) { dpWay = dp1 + dp2; dp1 = dp2; dp2 = dpWay; return climbStairsIter(n, dpWay, dp1, dp2); } else return dpWay; } int climbStairs(int n) { return climbStairsIter(n, 0,1,2); }
因为这里的参数涉及到执行前面顺序,所以最好还是单独列出来了,不过这样看来略不简洁呐。
代码
[code]class Solution { public: int climbStairs(int n) { int dp1 = 1, dp2 = 2, dpWay = 0; if (n <= 1) return dp1; if (n == 2) return dp2; while ((n--) - 2) { dpWay = dp1 + dp2; dp1 = dp2; dp2 = dpWay; } return dpWay; } };
相关文章推荐
- Finding all paths climbing stairs in one or two steps.
- jboss domain&cluster 配置
- Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
- SMPP网关模拟器系统发布(下载地址http://download.csdn.net/detail/dotphoenix/9408255)
- 百度地图 baidu map api应用
- 百度地图 baidu map api应用
- 进程通信:管道(pipe)和 unix域套接字(socketpair)区别
- 记一template 函数实现过程---std::iterator_traits在泛型算法中的应用
- 关于close_wait状态的问题分析
- [leetcode 256] Paint House
- AIX中的/etc/netsvc.conf及/etc/resolv.conf
- 赋予人工智能记忆的人,带你梳理深度学习核心算法
- VGG_19 train_vali.prototxt file
- 无法启动程序"D:\Desktop\code\MMI3\MainFrame\debug\MainFrame.exe" "D:\Desktop\code\bin\debug"不是有效的工作目录
- 每天一个设计模式: 责任链模式(Chain Of Responsibility)
- 【pymongo】连接认证 auth failed解决方法
- JAR export finished with warnings. See details for additional information
- ALOHA simulaiton仿真结果及分析
- [Machine Learning]朴素贝叶斯(NaiveBayes)
- Codeforces Educational Codeforces Round 5 E. Sum of Remainders 数学