当前位置:网站首页>LeetCode_474_ one and zero
LeetCode_474_ one and zero
2022-07-29 20:47:00 【Fitz1318】
题目链接
题目描述
给你一个二进制字符串数组 strs 和两个整数 m 和 n .
请你找出并返回 strs 的最大子集的长度,该子集中 最多 有 m 个 0 和 n 个 1 .
如果 x 的所有元素也是 y 的元素,集合 x 是集合 y 的 子集 .
示例 1:
输入:strs = ["10", "0001", "111001", "1", "0"], m = 5, n = 3
输出:4
解释:最多有 5 个 0 和 3 个 1 的最大子集是 {
"10","0001","1","0"} ,因此答案是 4 .
其他满足题意但较小的子集包括 {
"0001","1"} 和 {
"10","1","0"} .{
"111001"} 不满足题意,因为它含 4 个 1 ,大于 n 的值 3 .
示例 2:
输入:strs = ["10", "0", "1"], m = 1, n = 1
输出:2
解释:最大的子集是 {
"0", "1"} ,所以答案是 2 .
提示:
1 <= strs.length <= 6001 <= strs[i].length <= 100strs[i]仅由'0'和'1'组成1 <= m, n <= 100
解题思路
动态规划
- strThe elements in the array are equivalent to items,only one of each item
- m和nEquivalent to a two-dimensional backpack
动态规划五部曲
确定
dp数组和下标的含义dp[i][j]:最多有i个0和j个1的str的最大子集的大小
确定递推公式
dp[i][j] = Math,max(dp[i][j],dp[i - num0][j - num1] + 1)
dp数组初始化
- 因为物品价值不会是负数,所以初始为0即可
确定遍历顺序
- 外层for循环遍历物品,内层forThe loop traverses the knapsack capacity from back to front
举例推到dp数组

AC代码
class Solution {
public int findMaxForm(String[] strs, int m, int n) {
int[][] dp = new int[m + 1][n + 1];
int num0;
int num1;
dp[0][0] = 0;
for (String str : strs) {
num0 = 0;
num1 = 0;
for (char c : str.toCharArray()) {
if (c == '0') {
num0++;
} else {
num1++;
}
}
for (int i = m; i >= num0; i--) {
for (int j = n; j >= num1; j--) {
dp[i][j] = Math.max(dp[i][j], dp[i - num0][j - num1] + 1);
}
}
}
return dp[m][n];
}
}
边栏推荐
- Build your own image search system (1): 10 lines of code to search images by image
- 无偏估计和最小方差无偏估计简介
- C language advanced enumeration and joint
- scratch programming + elementary math
- ACM学习书籍简介
- MySQL 中的反斜杠 \\,怎么能这么坑?
- Verilog的时间格式系统任务----$printtimescale、$timeformat
- m10
- ESP8266-Arduino programming example-EEPROM read and write
- 并发编程学习笔记 之 常用并发容器的概念及使用方法
猜你喜欢

Omni-channel e-commerce | How can well-known domestic cosmeceuticals seize the opportunity to achieve rapid growth?

updatexml、extractvalue和floor报错注入原理
![[GXYCTF2019]禁止套娃](/img/91/3f64bebd13a8b13fbb387c2acf8618.png)
[GXYCTF2019]禁止套娃

"Additional price" can not exchange for safety, the death of Lexus LM, whose fault is it?

Agile Organization | The path for enterprises to overcome the impact of the digital wave

万字总结:分布式系统的38个知识点

C# CLI(公共语言基础结构)

ds1302——Bin brother 51

悲伤的摇滚乐

TDengine 助力西门子轻量级数字化解决方案
随机推荐
荣耀的野望:智慧世界的“高端平民”
ds1302——Bin brother 51
12437字,带你深入探究RPC通讯原理
m10
程序员如何提升自己写代码的能力?
Idea工具的使用
webUI测试框架设计思路详解
【体系结构 一 概述】
通过观测云监控器监控基础资源,自动报警
安全浏览器将拥有这些隐藏功能,让你玩转浏览器
Verilog的时间格式系统任务----$printtimescale、$timeformat
scratch 编程 + 小学数学
C language learning books (improvement)
基于STM32的RFID-RC522门禁系统
【Autosar vLinkGen 链接器脚本生成器】
搭建自己的以图搜图系统 (一):10 行代码以图搜图
cv2 imread()函数[通俗易懂]
C语言进阶 —— 枚举与联合
JS实现倒计时代码实例「建议收藏」
Xcode如何利用预览(Preview)让SwiftUI视图快速适配不同尺寸的设备