Starter

Climbing Stairs

Problem
LC 70
Difficulty
Easy
Pattern
DP
File
leetcode10ClimbingStairs.java
Path
pkg5leetcode/leetcode10ClimbingStairs.java
Package
pkg5leetcode
Command
java pkg5leetcode/leetcode10ClimbingStairs.java

You can climb 1 or 2 steps at a time. How many distinct ways to reach step n? INSIGHT: ways(n) = ways(n-1) + ways(n-2) -> it's Fibonacci.

Complexity
Time O(n), Space O(1).

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/leetcode10ClimbingStairs.java
1package pkg5leetcode;2 3/*4 * LeetCode 70: Climbing Stairs  (Easy)5 * ------------------------------------6 * You can climb 1 or 2 steps at a time. How many distinct ways to reach step n?7 *8 * INSIGHT: ways(n) = ways(n-1) + ways(n-2) -> it's Fibonacci.9 * COMPLEXITY: Time O(n), Space O(1).10 */11public class leetcode10ClimbingStairs {12 13    static int climbStairs(int n) {14        if (n <= 2) return n;15        int a = 1, b = 2;                 // ways to reach step 1 and step 216        for (int i = 3; i <= n; i++) { int c = a + b; a = b; b = c; }17        return b;18    }19 20    public static void main(String[] args) {21        check(climbStairs(1) == 1, "n=1");22        check(climbStairs(2) == 2, "n=2");23        check(climbStairs(3) == 3, "n=3");24        check(climbStairs(5) == 8, "n=5");25        check(climbStairs(10) == 89, "n=10");26        System.out.println("leetcode10ClimbingStairs: all tests passed");27    }28 29    static void check(boolean cond, String name) {30        if (!cond) throw new AssertionError("FAILED: " + name);31        System.out.println("  PASS " + name);32    }33}