70. Climbing Stairs (Easy)

https://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?

Note: Given n will be a positive integer.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

Solutions

1.

class Solution {
    public int climbStairs(int n) {
        if (n == 0 || n == 1) {
            return 1;
        }

        if (n == 2) {
            return 2;
        }

        // there are n stairs, actually, the walking path start from 0, the n
        int[] pathWay = new int[n];

        // stand still, 1 possibility
        pathWay[n - 1] = 1;

        // from n-2 to n, 2 possibility
        pathWay[n - 2] = 2;

        for (int i = n - 3; i >= 0; i--) {
            pathWay[i] = pathWay[i + 1] + pathWay[i + 2];
        }

        return pathWay[0];
    }
}

2.

class Solution {
    // pay attention that there is n steps, suppose the topmost stair numbered 0,
    // which means your starting stair's number is n, rather than n-1
    int[] pathWay;

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

        if (n == 2) {
            return 2;
        }

        pathWay = new int[n + 1];
        Arrays.fill(pathWay, -1);

        pathWay[1] = 1;
        pathWay[2] = 2;

        // set off from n to 0
        return walkThrough(n);
    }

    public int walkThrough(int n) {
        if (n <= 0) {
            return 0;
        }

        if (pathWay[n] >= 0) {
            return pathWay[n];
        }

        int p1 = walkThrough(n - 1);
        int p2 = walkThrough(n - 2);

        pathWay[n] = p1 + p2;

        return p1 + p2;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-03 11:01:17

results matching ""

    No results matching ""