tasks for today:
1. 322.零钱兑换
2. 279.完全平方数
3. 139.单词拆分
----------------------------------------------------------------------------
1. 322.零钱兑换
for 1-dim dp: the 01/complete decide the traverse sequence (descend/ascend) of backpack capability, the combination/permutation decide the choice of object-capability or capability-object.
deriving the number of solutions, should use dp[j] += d[j - nums[i]], with initialization of dp = [0] * (maxcapability+1) but with dp[0] = 1
min num of object (not the number of solutions): dp[j] = min(dp[j], dp[j-coins[i]]+1), with dp = [float('inf')] * (maxcap+1), dp[0] = 0
max value: dp[j] = max(dp[j], dp[j-weight[i]]+value[i]), with dp = [0] * (maxcap+1)
min value: dp[j] = min(dp[j], dp[j-weight[i]]+value[i]), with dp = [float('inf')] * (maxcap+1)
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for i in range(len(coins)):
for j in range(coins[i], amount+1):
dp[j] = min(dp[j], dp[j-coins[i]]+1)
if dp[-1] == float('inf'):
return -1
else:
return dp[-1]
2. 279.完全平方数
In this practice, the key is how to control the traverse of object, because there is not a specific given limit on the object weight, which need to be find by ourselves which is hidden in the description, that is the i**2 <= n;
class Solution:
def numSquares(self, n: int) -> int:
dp = [float('inf')] * (n+1)
dp[0] = 0
i = 1
while i**2 <= n:
for j in range(i**2, n+1):
dp[j] = min(dp[j], dp[j-i**2] + 1)
i += 1
if dp[-1] == float('inf'):
return -1
else:
return dp[-1]
3. 139.单词拆分
this practice has a reverse setting, which is not the usual setting that give the objects and try to derive the combination or the permutation for the arrangement of backpack. Instead, this practice give the permutation of backpack, and ask some questions about the objects.
One key pitfall in this practice is that the backpack, which is the string s in this practice, is a permutation problem.
In this practice, it is the first time so far for us to use boolen value for each entry in the dp list.
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
dp = [False] * (len(s) + 1)
dp[0] = True
for j in range(1, len(s)+1):
for i in range(j):
if (dp[i] and (s[i:j] in wordDict)):
dp[j] = True
break
return dp[-1]