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

LEETCODE: Climbing Stairs

2014-12-22 16:49 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?

如果样本数量更大一些,这个算法可能还是不能承受。

class Solution {
public:
int cnk(int n, int k) {
long long up = 1;
long long down = 1;
for(int ii = 0; ii < k; ii ++) {
down *= n - ii;
up *= k - ii;
// Maybe large than LONG_MAX.
if(down % 2 == 0 && up % 2 == 0) {
down /= 2;
up /= 2;
}
}
return down / up;
}
int climbStairs(int n) {
int maxnum2 = n / 2;
int result = 0;
for(int ii = 0; ii <= maxnum2; ii ++) {
result += cnk(n - ii, ii);
}

return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LEETCODE 算法 全排列