write once,run anywhere
  • Home
  • Tags
  • Archives

LeetCode [70] Climbing Stairs

Contents

  • Questions
  • Coding
    • python
    • Java

Questions¶

Difficulty: Easy

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?

Coding¶

python¶

# -*- coding: utf-8 -*-
class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n <= 1:
            return 1
        elif n == 2:
            return 2
        else:
            i, arr = 2, [1,2]
            while n > i:
                arr.append(arr[i-1]+arr[i-2])
                i += 1
            return arr[n-1]

Java¶

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

    }
}

Related Posts

  • LeetCode [1] Two Sum
  • LeetCode [2] Add Two Numbers
  • LeetCode [58] Length of Last Word
  • LeetCode [190] Reverse Bits
  • LeetCode [151] Reverse Words in a String

  • « LeetCode [3] Longest Substring Without Repeating Characters
  • LeetCode [237] Delete Node in a Linked List »

Published

8月 20, 2016

Last Updated

8月 20, 2016

Category

Linux

Tags

  • LeetCode 13

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor