[PYTHON] Let Code Day 25 "70. Climbing Stairs" starting from scratch

Overview

It seems that coding tests are conducted overseas in interviews with engineers, and in many cases, the main thing is to implement specific functions and classes according to the theme.

As a countermeasure, it seems that a site called Let Code will take measures.

A site that trains algorithmic power that can withstand coding tests that are often done in the home.

I think it's better to have the algorithm power of a human being, so I'll solve the problem irregularly and write down the method I thought at that time as a memo.

Leetcode

Leet Code Table of Contents Starting from Zero

Last time Leet Code Day24 starting from zero "21. Merge Two Sorted Lists"

Basically, I would like to solve the easy acceptance in descending order.

Twitter I'm doing it.

problem

70. Climbing Stairs The difficulty level is easy. Excerpt from Top 100 Liked Questions.

I think this is a familiar problem for those who have taken the junior high school exam. Actually, there is a very simple solution, but I will explain it in the solution.

When you climb the stairs, you can climb one or two steps. Given the natural number n, please answer how many ways you can reach the summit.

Example 1:

Input: 2 output: 2

In the case of 2, there is a method of climbing 2 steps at a stretch and a method of climbing 1 step twice, so 2 is returned.

Example 2:

Input: 3 Output: 3

In the case of 3, 3 is returned because there are three methods: repeating one step at a time, going up one step and going up two steps, and going up two steps and going up one step.

solution

Actually, this is a problem with the Fibonacci sequence. You may have seen it while studying the number of cases.

By the way, the Fibonacci sequence is 1,1,2,3,5,8,13,21,34,55, And so on, it is a sequence in which the sum of the previous two numbers becomes the next number.

Let's consider the case where there are 3 steps as in the example. In this case, it depends on the case at the first stage. There is a pattern of climbing one step or two steps. If you climb two steps, you will inevitably have one option because there are only one stairs left. On the other hand, if 1 is selected, there are 2 steps left, that is, 2 ways as shown in the example. The sum of these additions is the answer for each case, and this is a typical example of the Fibonacci sequence as described above.

Try other numbers as well. Let's say it has 4 steps.

Then select 1st step and 2nd step first. The first is the case of 1 step, but the rest is 3 steps. In other words, you can use the 3 ways of the previous 3 steps as they are. And in the case of 2 steps, the rest is 2 steps. In other words, there are two ways. There are 3 ways + 2 ways, so there are 5 ways.

If you add one staircase, it will increase to 8, and if you add another step, it will increase to 13 ...

Once you understand the structure of this addition, all you have to do is code the law.

As a simple example

class Solution:
    def climbStairs(self, n: int) -> int:
        if n <= 1:
            return n
        num1, num2 = 0, 1
        for i in range(n):
            num1, num2 = num2, num1+num2
        return num2
# Runtime: 32 ms, faster than 39.40% of Python3 online submissions for Climbing Stairs.
# Memory Usage: 13.7 MB, less than 5.97% of Python3 online submissions for Climbing Stairs.

This is the general solution. However, when I looked at the discuss, there was a faster way to write it.

from functools import lru_cache

class Solution:
    @lru_cache(None)
    def climbStairs(self, n):
        if n == 1:
            return 1
        elif n == 2:
            return 2
        else:
            return self.climbStairs(n-1) + self.climbStairs(n-2)
# Runtime: 24 ms, faster than 91.08% of Python3 online submissions for Climbing Stairs.
# Memory Usage: 13.9 MB, less than 5.97% of Python3 online submissions for Climbing Stairs.

It's really fast ...

By the way, what is lru_cache? So I quietly looked it up in the Official Documents.

@functools.lru_cache(user_function) @functools.lru_cache(maxsize=128, typed=False) A decorator that wraps a function in a callable object for memoization and saves up to maxsize recent calls. You can save time when you regularly call expensive functions or functions that are bound to I / O with the same arguments.

Since a dictionary is used to cache the results, the function's positional and keyword arguments must be hashable.

If the argument patterns are different, they are considered different calls and will be separate cache entries. For example, f (a = 1, b = 2) and f (b = 2, a = 1) are two separate cache entries because the order of the keyword arguments is different. .....

The LRU (least recently used) cache is most efficient when the latest call is most likely to be called again (for example, the most popular articles on the news server tend to change daily). .. The cache size limit ensures that the cache does not grow beyond the limits of long-term processes such as web servers.

In general, the LRU cache should only be used when you want to reuse the previously calculated value. So there is no point in caching functions that have side effects, functions that require you to create a separate mutable object for each call, or impure functions like time () or random ().

In other words, since the result of the called function is cached using a dictionary, if the cached result is called even in the latest call, the efficiency at the time of execution will increase.

I didn't know it, so I learned a lot, but it's important to see the discussion.

Recommended Posts

Let Code Day 25 "70. Climbing Stairs" starting from scratch
Let Code Day75 starting from scratch "15.3 Sum"
Let Code Day 29 "46. Permutations" starting from scratch
Let Code Day 27 "101. Symmetric Tree" starting from scratch
Let Code Day 41 "394. Decode String" starting from scratch
Let Code Day69 starting from scratch "279. Perfect Squares"
Let Code Day 34 starting from scratch "118. Pascal's Triangle"
Let Code Day85 starting from scratch "6. ZigZag Conversion"
Let Code Day20 starting from scratch "134. Gas Station"
Let Code Day 88 "139. Word Break" starting from scratch
Let Code Day 28 "198. House Robber" starting from scratch
Let Code Day 39 "494. Target Sum" starting from scratch
Let Code Day 36 "155. Min Stack" starting from scratch
Let Code Day 17 "169. Majority Element" starting from scratch
Let Code Day 33 "1. Two Sum" starting from scratch
Let Code Day8 starting from scratch "1302. Deepest Leaves Sum"
Let Code Day 22 starting from scratch "141. Linked List Cycle"
Let Code Day 30 starting from scratch "234. Palindrome Linked List"
Let Code Day 32 "437. Path Sum III" starting from scratch
Let Code Day68 starting from scratch "709. To Lower Case"
Let Code Day 26 starting from scratch "94. Binary Tree Inorder Traversal"
Let Code Day 46 starting from scratch "406. Queue Reconstruction by Height"
Let Code Day 38 starting from scratch "208. Implement Trie (Prefix Tree)"
Let Code Day3 starting from scratch "1313. Decompress Run-Length Encoded List"
Let Code Day 65 "560. Subarray Sum Equals K" starting from scratch
Let Code Day4 starting from scratch "938. Range Sum of BST"
Let Code Day 77 starting from scratch "1502. Can Make Arithmetic Progression From Sequence"
Let Code Day 76 starting from scratch "3. Longest Substring Without Repeating Characters"
Let Code Day58 Starting from Zero "20. Valid Parentheses"
Let Code Day16 Starting from Zero "344. Reverse String"
Let Code Day49 starting from zero "1323. Maximum 69 Number"
Let Code Day89 "62. Unique Paths" Starting from Zero
Let Code Day 55 "22. Generate Parentheses" Starting from Zero
Let Code Day18 starting from zero "53. Maximum Subarray"
Let Code Day 13 "338. Counting Bits" Starting from Zero
Let Code Day71 Starting from Zero "1496. Path Crossing"
Let Code Day 61 "7. Reverse Integer" starting from zero
Let Code Day 82 "392. Is Subsequence" Starting from Zero
Let Code Day51 Starting from Zero "647. Palindromic Substrings"
Let Code Day 50 "739. Daily Temperatures" Starting from Zero
Let Code Day 15 "283. Move Zeroes" starting from zero
Let Code Day14 starting from zero "136. Single Number"
Let Code Day 9 "701. Insert into a Binary Search Tree" starting from scratch
Let Code Day 80 "703. Kth Largest Element in a Stream" starting from scratch
Let Code Day 66 "438. Find All Anagrams in a String" starting from scratch
Let Code Day 43 "5. Longest Palindromic Substring" Starting from Zero
Let Code Day 42 "2. Add Two Numbers" Starting from Zero
Let Code Day57 Starting from Zero "35. Search Insert Position"
Let Code Day47 Starting from Zero "14. Longest Common Prefix"
Let Code Day78 Starting from Zero "206. Reverse Linked List"
Let Code Day 90 starting from scratch "101 11. Capacity To Ship Packages Within D Days"
Let Code Day 44 "543. Diameter of Binary Tree" starting from zero
Let Code Day 64 starting from zero "287. Find the Duplicate Number"
Let Code Day 84 starting from zero "142. Linked List Cycle II"
Let Code Day24 Starting from Zero "21. Merge Two Sorted Lists"
Let Code Day12 Starting from Zero "617. Merge Two Binary Trees"
Let Code Day2 Starting from Zero "1108. Defanging an IP Address"
Let Code Day70 Starting from Zero "295. Find Median from Data Stream"
Let Code Day81 "347. Top K Frequent Elements" Starting from Zero
Let Code Day48 Starting from Zero "26. Remove Duplicates from Sorted Array"
Let Code Day87 Starting from Zero "1512. Number of Good Pairs"