mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
Update 0474.一和零.md
添加一和零 python3 版本
This commit is contained in:
@ -191,6 +191,31 @@ class Solution {
|
||||
|
||||
Python:
|
||||
|
||||
```python3
|
||||
class Solution:
|
||||
def countBinary(self, s: str) -> (int, int):
|
||||
zeros, ones = 0, 0
|
||||
for c in s:
|
||||
if c == '0':
|
||||
zeros += 1
|
||||
else:
|
||||
ones += 1
|
||||
return zeros, ones
|
||||
|
||||
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
|
||||
dp = [[0]*(n + 1) for _ in range(m + 1)] # 默认初始化0
|
||||
# 遍历物品
|
||||
for i in range(len(strs)):
|
||||
# num_zeros = strs[i].count('0')
|
||||
# num_ones = strs[i].count('1')
|
||||
num_zeros, num_ones = self.countBinary(strs[i])
|
||||
# 遍历背包容量且从后向前遍历!
|
||||
for j in range(m, num_zeros - 1, -1):
|
||||
for i in range(n, num_ones - 1, -1):
|
||||
dp[j][i] = max(dp[j - num_zeros][i - num_ones] + 1, dp[j][i])
|
||||
return dp[m][n]
|
||||
```
|
||||
|
||||
|
||||
Go:
|
||||
|
||||
|
Reference in New Issue
Block a user