[关闭]
@Lin-- 2020-02-14T14:06:00.000000Z 字数 718 阅读 296

findMaxForm

Leetcode


给出一个数组,两个整数,数组里的元素是0和1组合的字符串。两个整数代表拥有的0和1的个数,要求用已有的0和1,凑出数组里有de


该问题是变式的0-1背包问题,只不过其背包空间是二维的。那么再加上物品,这是一个三维空间的背包问题。但是,可以从利用基本0-1背包问题空间优化时的思路,将物品那一维省略,用一张二维表记录当前背包载重的价值。其中:行数的0的个数,列数是1的个数。

  1. '''
  2. # File: findMaxForm.py
  3. # Author: 0HP
  4. # Date: 202002110
  5. # Purpose: solve the problem in website: https://leetcode.com/problems/ones-and-zeroes/
  6. '''
  7. class Solution:
  8. def findMaxForm(self, strs, m: int, n: int) -> int:
  9. #build the space of bag which has 2 orders
  10. #row is n,col is m
  11. dp=[[0 for i in range(n+1)]for j in range(m+1)]
  12. for i in strs:
  13. zeros,ones,zero,one=m,n,0,0
  14. for j in i:
  15. if j=="1":#"1"'s counts
  16. one+=1
  17. if j=="0":#"0"'s counts
  18. zero+=1
  19. while not zeros<zero:
  20. ones=n
  21. while not ones<one:
  22. dp[zeros][ones]=max(dp[zeros][ones],dp[zeros-zero][ones-one]+1)
  23. ones-=1
  24. zeros-=1
  25. return dp[-1][-1]
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注