背包问题
0-1背包问题
状态转移方程dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - w[i - 1]] + v[i - 1]),i代表第几个物品,j代表背包容量,w[i - 1],v[i - 1]代表第i个物品的重量和价值。
#背包问题I
class Solution:
"""
@param m: An integer m denotes the size of a backpack
@param A: Given n items with size A[i]
@return: The maximum size
"""
def backPack(self, m, A):
# write your code here
dp = [0 for _ in range(m + 1)]
for i in range(len(A)):
for j in range(m, A[i] - 1, -1):
dp[j] = max(dp[j], dp[j - A[i]] + A[i])
return dp[m]
#n = len(A)
#dp = [[0] * (m + 1) for _ in range(n + 1)]
#for i in range(1, n + 1):
# for j in range(1, m + 1):
# dp[i][j] = dp[i - 1][j]
# if j >= A[i - 1]:
# dp[i][j] = max(dp[i-1][j], dp[i-1][j - A[i - 1]] + A[i - 1])
#return dp[n][m]
#背包问题II
class Solution:
"""
@param m: An integer m denotes the size of a backpack
@param A: Given n items with size A[i]
@param V: Given n items with value V[i]
@return: The maximum value
"""
def backPackII(self, m, A, V):
# write your code here
#滚动数组:时间O(Am)空间O(m)
#dp = [0 for _ in range(m + 1)]
#n = len(A)
#for i in range(n):
# for j in range(m, A[i]-1, -1):
# dp[j] = max(dp[j], dp[j - A[i]] + V[i])
#return dp[m]
#时间复杂度O(Am)空间O(Am)
dp = [[0] * (m + 1) for _ in range(len(A) + 1)]
for i in range(1, len(A) + 1):
for j in range(1, m + 1):
if A[i - 1] > j:
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = max(dp[i - 1][j], dp[i-1][j - A[i-1]] + V[i - 1])
return dp[len(A)][m]
# 背包问题V
class Solution:
"""
@param nums: an integer array and all positive numbers
@param target: An integer
@return: An integer
"""
def backPackV(self, nums, target):
# write your code here
#n = len(nums)
#dp = [[0] * (target + 1) for _ in range(n + 1)]
#dp[0][0] = 1
#for i in range(1, n + 1):
# for j in range(target + 1):
# dp[i][j] = dp[i - 1][j]
# if j >= nums[i - 1]:
# dp[i][j] += dp[i - 1][j - nums[i - 1]]
#return dp[n][target]
#滚动数组
n = len(nums)
dp = [0 for _ in range(target + 1)]
dp[0] = 1
for i in range(n):
for j in range(target, -1, -1):
if j >= nums[i]:
dp[j] += dp[j - nums[i]]
return dp[target]
#背包问题 IX
class Solution:
"""
@param n: Your money
@param prices: Cost of each university application
@param probability: Probability of getting the University's offer
@return: the highest probability
"""
def backpackIX(self, n, prices, probability):
# write your code here
p = len(prices)
dp = [0 for _ in range(n + 1)]
for i in range(p):
for j in range(n, prices[i] - 1, -1):
dp[j] = max(dp[j], 1 - (1 - dp[j - prices[i]]) * (1 - probability[i]))
return float(dp[n])
#卡牌游戏II
class Solution:
"""
@param cost: costs of all cards
@param damage: damage of all cards
@param totalMoney: total of money
@param totalDamage: the damage you need to inflict
@return: Determine if you can win the game
"""
def cardGame(self, cost, damage, totalMoney, totalDamage):
# Write your code here
n = len(cost)
dp = [0 for _ in range(totalMoney + 1)]
for i in range(n):
for j in range(totalMoney, cost[i]-1, -1):
dp[j] = max(dp[j], dp[j - cost[i]] + damage[i])
return dp[totalMoney] >= totalDamage