您的位置:首页 > 编程语言 > C语言/C++

LeetCode 70 — Climbing Stairs(C++ Java Python)

2014-03-20 22:17 921 查看
题目:http://oj.leetcode.com/problems/climbing-stairs/

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步到达顶端。

每次可以爬上1或2级。有多少种不同的方式到达顶端?

分析:
        f(n)=f(n-1)+f(n-2)。自底向上。
C++实现:
class Solution {
public:
int climbStairs(int n) {
int a[n + 1];
a[0] = 1;
a[1] = 1;

for(int i = 2; i <= n; ++i)
{
a[i] = a[i - 1] + a[i - 2];
}

return a
;
}
};
Java实现:
public class Solution {
public int climbStairs(int n) {
if (n == 0) {
return 1;
}

int[] a = new int[n + 1];

a[0] = 1;
a[1] = 1;

for (int i = 2; i <= n; ++i) {
a[i] = a[i - 1] + a[i - 2];
}

return a
;
}
}
Python实现:
class Solution:
# @param n, an integer
# @return an integer
def climbStairs(self, n):
a = []
a.append(1)
a.append(1)

for i in range(2, n + 1):
a.append(a[i - 1] + a[i - 2])

return a
        感谢阅读,欢迎评论!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode