TypechoJoeTheme

IT技术分享

统计

[LeetCode 70] Climbing Stairs [Java] [Runtime : 0MS]

2017-07-25
/
0 评论
/
814 阅读
/
正在检测是否收录...
07/25

1. Description

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?

2. Runtime Distribution

3. Submission Details

5. Code

public int climbStairs(int n)
{
    if (n == 1 || n == 2) {
        return n;
    }

    int pre1 = 2, pre2 = 1, sum = 0;

    for (int k = 3; k <= n; k++) {
        sum = pre1 + pre2;
        pre2 = pre1;
        pre1 = sum;
    }
    return sum;
}

6.Test

public class LeetCode0070 {

    public int climbStairs(int n)
    {
        if (n == 1 || n == 2) {
            return n;
        }

        int pre1 = 2, pre2 = 1, sum = 0;

        for (int k = 3; k <= n; k++) {
            sum = pre1 + pre2;
            pre2 = pre1;
            pre1 = sum;
        }
        return sum;
    }

    public static void main(String[] args)
    {
        LeetCode0070 leetcode = new LeetCode0070();
        System.out.println(leetcode.climbStairs(4));
    }
}
Math
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/654/(转载时请注明本文出处及文章链接)