LeetCode 题解(226) : Climbing Stairs

来源:互联网 发布:清华 王奇 知乎 编辑:程序博客网 时间:2024/05/21 17:30

题目:

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?

题解:

C++版:

class Solution {public:    int climbStairs(int n) {        if(n == 0 ||  n == 1)            return n;                    int* ways = new int[n];        ways[0] = 1;        ways[1] = 2;        for(int i = 2; i <= n - 1; i++)            ways[i] = ways[i - 1] + ways[i - 2];        return ways[n - 1];    }};

Java版:

public class Solution {    public int climbStairs(int n) {        if(n == 0 || n == 1)            return n;        int[] ways = new int[n];        ways[0] = 1;        ways[1] = 2;        for(int i = 2; i <= n - 1; i++)            ways[i] = ways[i - 1] + ways[i - 2];        return ways[n - 1];    }}

Python版:

class Solution(object):    def climbStairs(self, n):        """        :type n: int        :rtype: int        """        if n == 0:            return 0        if n == 1:            return 1                    step = [0] * n        step[0], step[1] = 1, 2        i = 2        while i <= n - 1:            step[i] = step[i - 1] + step[i - 2]            i += 1        return step[n - 1]

0 0
原创粉丝点击