您的位置:首页 > 大数据 > 人工智能

Climb Stairs

2016-07-26 20:34 375 查看

Climb Stairs

作者:money

标签:leetcode,C++

问题:

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?

问题分析:

这个问题被分到easy中,被我用排列组合复杂方法去思考。

题目解法还是很容易的。n步的梯子假设有F(n)的走法,如果最后一步为1步,剩下n-1步有F(n-1)种走法,最后一步为2步,剩下n-2步有F(n-2)种走法,因此递推公式是斐波那契数列:

F(n)=F(n−1)+f(n−2)

排列组合做法:

根据走两步的次数k∈[0,n2],计算组合的个数,再通过求和获得总的走法:

sum=\sum_{k=0}^{\frac{n}{2}} a_k


关键是需要找到ak的计算方式。

假设n步的梯子,假设走k个2步,则有n-2k个1步,此时我们走法次数是

ak=Cn−2kn−k

其中:

Crn=n!r!(n−r)!

为什么会是这个公式呢,解释如下:

如果有k个两步,则会有n-2k个1步,保证加起来总数是n步。

然后我们要计算的就是在n-k步中,怎么去组合1步(n-2k)。

因此就是上述的公式。

然后计算递归公式:

ak+1ak=Cn−2k−2n−k−1Cn−2kn−k

ak+1=(n−2k)(n−2k−1)(n−k)(k+1)ak

代码

使用斐波那契数列,递归求第n项:

#include <iostream>
#include <string>
#include <vector>
#include <math.h>
// submit these code to leetcode
// begin
using namespace std;
class Solution {
public:
int climbStairs(int n) {
int a1,a2;
a1=1,a2=2;
int sum=3;
if(n==1)
sum=1;
else if(n==2)
sum=2;
else
for(int i=2;i<n;i++)
{
sum=a2+a1;
a1 = a2;
a2=sum;
}
return sum;
}
};

// end
// submit these code to leetcode

int main()
{
Solution s;
//test case
int a,b;
cin>>b;
a=s.climbStairs(b);
std::cout<<a<<" "<<endl;
return 0;
}


利用排列组合求和:

#include <iostream>
#include <string>
#include <vector>
#include <math.h>
// submit these code to leetcode
// begin
using namespace std;

class Solution {
public:
int climbStairs(int n) {
long sum=1;
double ai=1.0;
for(int i=0;i<(n)/2;i++)
{
ai=ai*(n-2*i)/(n-i)*(n-2*i-1)/(i+1);
sum=sum+ai;
}
return sum;
}
};

// end
// submit these code to leetcode

int main(){
Solution s;
int test;
int a;
cin>>test;
a=s.climbStairs(test);
//test case
cout<<"sum="<<a<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: