目录
学习目标
学习内容
1049. 最后一块石头的重量 II
494. 目标和
474.一和零
学习目标
- 1049. 最后一块石头的重量 II
- 494. 目标和
- 474.一和零
学习内容
1049. 最后一块石头的重量 II
1049. 最后一块石头的重量 II - 力扣(LeetCode)https://leetcode.cn/problems/last-stone-weight-ii/
class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
amount = sum(stones)
target = amount//2
n = len(stones)
dp = [0]*(target+1)
for i in range(n):
for j in range(target,stones[i]-1,-1):
dp[j] = max(dp[j],dp[j-stones[i]]+stones[i])
#print(dp)
return amount-2*dp[-1]
494. 目标和
494. 目标和 - 力扣(LeetCode)https://leetcode.cn/problems/target-sum/
class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
amount = sum(nums)
if (amount-target)%2!=0 or amount<abs(target):return 0
n = len(nums)
target = (amount-target)//2
dp = [0]*(target+1)
dp[0] = 1
for i in range(n):
for j in range(target,nums[i]-1,-1):
dp[j] +=dp[j-nums[i]]
#print(dp)
return dp[target]
474.一和零
474. 一和零 - 力扣(LeetCode)https://leetcode.cn/problems/ones-and-zeroes/
class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
# dp[k][i][j] 表示 用到个k个元素当前装满i个0和j个1的最长子集长度
# dp[k][i][j] = max(dp[k-1][i][j],dp[k-1][i-strs[i].count(0)][j-strs[i].count(1)]+1)
# 初始化 dp[i][j]根据第一个元素进行初始化
# 顺序 先物品 后背包 从上到下 从右到左(为了元素只用了一次)
dp = [[0]*(n+1)for _ in range(m+1)]
for item in strs:
num0 = 0
num1 = 0
for c in item:
if c=="0":
num0+=1
else:
num1+=1
for i in range(m,num0-1,-1):
for j in range(n,num1-1,-1):
dp[i][j] = max(dp[i][j],dp[i-num0][j-num1]+1)
return dp[-1][-1]