开始第七天的练习!
You are climbing a staircase. It takes
n
steps to reach the top.Each time you can either climb
1
or2
steps. In how many distinct ways can you climb to the top?
在刚进行动态规划的练习时候,曾经用简单的方法做过这道题。但是现在学了背包问题的思想,可以在原题上进行改动:一步一个台阶,两个台阶,三个台阶,…,直到 m个台阶。问有多少种不同的方法可以爬到楼顶呢?
1阶,2阶,… m阶就是物品,楼顶就是背包。
每一阶可以重复使用,例如跳了1阶,还可以继续跳1阶。
问跳到楼顶有几种方法其实就是问装满背包有几种方法。
- 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]
You are given an integer array
coins
representing coins of different denominations and an integeramount
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.
由于硬币总数量无限,因此这是完全背包问题。
- 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]
Given an integer
n
, return the least number of perfect square numbers that sum ton
.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
, and16
are perfect squares while3
and11
are not.
仍然是完全背包问题
- 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]