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

【Leetcode】Climbing Stairs

2014-03-19 22:24 316 查看
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 有两种途径:从 n - 1 走一步 or 从 n - 2 走两步.

所以 f(n) = f(n - 1) + f (n - 2), 即斐波那契数列。可以迭代求解或者直接用通项公式。

class Solution {
public:
int climbStairs(int n) {
const double s = sqrt(5);
return floor((pow((1+s)/2, n+1) + pow((1-s)/2, n+1))/s + 0.5);
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: