【0-1 knapsack】 474. Ones and Zeroes
来源:互联网 发布:房子短租软件 编辑:程序博客网 时间:2024/06/02 05:43
Description:
In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue.
For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s.
Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. Each 0 and 1 can be used at most once.
解题思路:
0/1背包问题的变种,用二维变量来表示背包的容量,即0和1的数量值。
- 统计各个字符串中0和1的数量
- 对于满足数量要求的背包元素,即dp[i][j],从大到小迭代更新dp[i][j]值
- 最后的dp[m][n]值即为最多可容纳的字符串数量值
class Solution(object): def findMaxForm(self, strs, m, n): dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)] for s in strs: c0 = 0 c1 = 0 for c in s: if c == "0": c0 += 1 else: c1 += 1 for i in range(m, c0 - 1, -1): for j in range(n, c1 - 1, -1): dp[i][j] = max(dp[i - c0][j - c1] + 1, dp[i][j]) return dp[m][n]
0 0
- 【0-1 knapsack】 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- jQuery的remove()和empty()的区别
- 用WritableSheet编辑多个sheet下载的问题
- Win 32 API中对文件的操
- 用mark&sweep回收算法实现个C保守垃圾收集器
- 千里之行始于足下
- 【0-1 knapsack】 474. Ones and Zeroes
- EM算法求解混合伯努利模型
- Lottie初级教程:打造iOS APP完美动画
- NOIP 2001-2——最大公约数和最小公倍数问题(简单推导/分解质因数)
- 信号集操作函数,信号未决、阻塞、递达
- phpcms 推荐位在首页显示错误问题
- POJ2395 Out of Hay
- EPPLUS 分组
- 关于安装vs小助手遇到的遇到一些小问题