2016.6.21——Climbing Stairs
2024-09-28 06:07:33
Climbing Stairs
本题收获:
1.斐波那契函数f(n) = f(n-1) + f(n -2)
题目:
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阶台阶,每次可以走2步或者1步,问有多少种方法到达顶端
思路:
leetcode:是个斐波那契函数的迭代
对于第n阶来说,有两种方法,从n-1 走 1阶 到n, 从n-2走2阶到n(刚开始想从n-2处到n 可以走1次2步 和 2次 1步,但是走1次一步不就成了n-1到n了, 重复)
代码:
class MyClass
{
public:
int clambingStairs(int n)
{
if (n == ) return ;
if (n == ) return ;
if (n == ) return ; int f2 = , f1 = , f = ;
for (int i = ; i < n; i++)
{
f = f1 + f2; //f2可以看做f(n-2)
f2 = f1; //f1看做f(n-1)
f1 = f; //f看做f(n)
}
return f;
}
};
我的测试代码:
// Climbing Stairs.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include "iostream"
using namespace std; class MyClass
{
public:
int clambingStairs(int n)
{
if (n == ) return ;
if (n == ) return ;
if (n == ) return ; int f2 = , f1 = , f = ;
for (int i = ; i < n; i++)
{
f = f1 + f2; //f2可以看做f(n-2)
f2 = f1; //f1看做f(n-1)
f1 = f; //f看做f(n)
}
return f;
}
}; int _tmain(int argc, _TCHAR* argv[])
{
int n = ;
cin >> n;
MyClass solution;
int m = ;
m = solution.clambingStairs(n);
cout << m << endl;
system("pause");
return ;
}
最新文章
- iOS之UILabel的自动换行
- [Java 缓存] Java Cache之 Guava Cache的简单应用.
- python 以及其他java php等在ubuntu上切换的命令
- KVC 与 KVO
- 利用javascript对提交数据验证
- Django-Json 数据返回
- topcoder SRM 624 DIV2 CostOfDancing
- Python 学习之 NumPy
- 滚动条滚动事件 js
- 2.2安装JDK
- 隐马尔可夫模型(HMM)
- no datanode to stop
- 初步接触html心得
- 计蒜客 2017 NOIP 提高组模拟赛(四)Day1 T2 小X的密室
- C#,WPF中使用多文本显示数据,并对其数据进行关键字高亮等操作
- HTTP协议详解(一)
- Modbus库开发笔记:Modbus ASCII Slave开发
- Resolved validation conflict with readonly
- sql server 的变量
- java中的变量和常量
热门文章
- MachineLearning Exercise 7 : K-means Clustering and Principle Component Analysis
- 跳转不同包时候 需要先指定该包的namespace 注意 先跳转 即加上/
- springmvc+json 前后台数据交互
- Nginx+Tomcat搭建高性能负载均衡集群--Windows本地测试版
- Educational Codeforces Round 56 Div. 2 翻车记
- 理解Restful api的意义
- 【刷题】BZOJ 5091 [Lydsy1711月赛]摘苹果
- 【BZOJ1914】数三角形(组合数,极角排序)
- BZOJ 2243 染色 | 树链剖分模板题进阶版
- Integer to Roman - LeetCode