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

Leetcode: Climbing Stairs

2014-01-07 20:52 423 查看
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?

算是简单的DP,如果想不到会感觉没思路。 最懒的方法是递归,不过时间过不了。

class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {
return n;
}

return (climbStairs(n-1) + climbStairs(n-2));
}
};
改成迭代就可以啦,利用前面计算过的结果。

class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {
return n;
}

int sn, sn2 = 1, sn1 = 2;
for (int i = 3; i <= n; ++i) {
sn = sn2 + sn1;
sn2 = sn1;
sn1 = sn;
}

return sn;
}
};

=====================第二次=====================

class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {
return n;
}

int n1 = 1;
int n2 = 2;
int ways = 0;
for (int i = 3; i <= n; ++i) {
ways = n1 + n2;
n1 = n2;
n2 = ways;
}

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