LeetCode Day 45 Dynamic Programming (7/17)

4 minute read

Published:

Move to 7th day practice!

Question 1

70. Climbing Stairs

You are climbing a staircase. It takes n steps to reach the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

When I was first practising dynamic programming, I used to do this problem in a simple way. But now that I have learnt the idea of the Knapsack problem, I can make changes to the original problem: one step, two steps, three steps, …, until m steps. Ask how many different ways there are to climb to the top of the building.

1 step, 2 steps, … m steps is the item and the roof is the backpack. Each step can be reused, e.g. if you jump 1 step, you can continue to jump 1 step. Asking how many ways there are to jump to the roof is really asking how many ways there are to fill the backpack.

  1. Determine the dp array and what the subscripts mean
    1. dp[i]: there are dp[i] ways to climb to the top of a building with i steps.
  2. Determine the recursive formula
    1. There are several sources of dp[i] for this problem, dp[i - 1], dp[i - 2], dp[i - 3], etc., i.e.: dp[i - j]
    2. Then the recursive formula is: dp[i] += dp[i - j]
  3. How the dp array is initialised,
    1. Since the recursive formula is dp[i] += dp[i - j], then dp[0] must be 1. dp[0] is the base of all values in the recursion, and if dp[0] is 0, then all other values are 0.
    2. Subscript non-0 dp[i] initialised to 0, because dp[i] is accumulated by dp[i-j], dp[i] itself is 0 so as not to affect the results.
  4. Determining the traversal order
    1. This is a Knapsack problem, i.e., steps 1 and 2 and steps 2 and 1 are both three steps up, but they are not the same!
    2. So we need to put the target in the outer loop and the nums in the inner loop.
    3. Each step can be taken multiple times, which is fully backpacked, and the inner loop needs to be traversed from front to back.
  5. Example to derive the dp array
class Solution:
    def climbStairs(self, n: int) -> int:
        dp = [0]*(n+1)
        dp[0] = 1
 
        for i in range(n+1):
            for j in range(1,m+1):
                if i - j >= 0:
                    dp[i] += dp[i-j]
 
        return dp[-1]

Question 2

322. Coin Change

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

Since the total number of coins is infinite, this is a complete Knapsack problem.

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        dp = [float('inf')] * (amount + 1)  
        dp[0] = 0  
 
        for coin in coins:  
            for i in range(coin, amount + 1):  
                if dp[i - coin] != float('inf'): 
                    dp[i] = min(dp[i - coin] + 1, dp[i]) 
 
        if dp[amount] == float('inf'):  
            return -1
        return dp[amount]  

Question 3

279. Perfect Squares

Given an integer n, return the least number of perfect square numbers that sum to n.

A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

Still the type of complete Knapsack problem.

class Solution:
    def numSquares(self, n: int) -> int:
        dp = [float('inf')] * (n + 1)
        dp[0] = 0
 
        for i in range(1, n + 1): 
            for j in range(1, int(i ** 0.5) + 1):  
                dp[i] = min(dp[i], dp[i - j * j] + 1)
 
        return dp[n]