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

【LeetCode】Climbing Stairs

2014-03-12 22:20 281 查看
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?
Bad solution↓

class Solution {
public:
int climbStairs(int n)
{
int ways = 0;
int x = 0;
int y = 0;
for(int i = 0; i <= n; i++)
{
x = i;
if( (n-x) % 2 == 0)
{
y = (n-x) / 2;
if(x == 0 || y == 0)
ways++;
else
{
int tmp = x+y;
long long sum = 1;
int cnt = 0;
int minVal = x > y?y:x;
while(cnt < minVal)
{
sum *= tmp;
tmp--;
cnt++;
if(cnt <= minVal)
{
sum /= cnt;
}
}
ways += sum;
}
}
}
return ways;
}
};
此题有排列组合运算,为了防止溢出:

1:sum类型为long long,最大值9223372036854775807

2:除的操作在运算中途就进行

此题是一个斐波那契数列,利用递归,迭代及公式法可以求解。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: