474:一和零

This commit is contained in:
huangge1199@hotmail.com 2021-06-06 22:45:41 +08:00
parent 242940b75b
commit 3f63208a16
3 changed files with 113 additions and 1 deletions

View File

@ -0,0 +1,74 @@
//给你一个二进制字符串数组 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 <= 600
// 1 <= strs[i].length <= 100
// strs[i] 仅由 '0' '1' 组成
// 1 <= m, n <= 100
//
// Related Topics 动态规划
// 👍 481 👎 0
package leetcode.editor.cn;
//474:一和零
class OnesAndZeroes {
public static void main(String[] args) {
//测试代码
Solution solution = new OnesAndZeroes().new Solution();
System.out.println(solution.findMaxForm(new String[]{"10", "0001", "111001", "1", "0"}, 5, 3));
System.out.println(solution.findMaxForm(new String[]{"10", "0", "1"}, 1, 1));
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int findMaxForm(String[] strs, int m, int n) {
int[][] dp = new int[m+1][n+1];
for (String str : strs) {
int size = str.length();
int num0 = str.replace("1", "").length();
int num1 = size - num0;
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];
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,38 @@
<p>给你一个二进制字符串数组 <code>strs</code> 和两个整数 <code>m</code><code>n</code></p>
<div class="MachineTrans-Lines">
<p class="MachineTrans-lang-zh-CN">请你找出并返回 <code>strs</code> 的最大子集的大小,该子集中 <strong>最多</strong><code>m</code><code>0</code><code>n</code><code>1</code></p>
<p class="MachineTrans-lang-zh-CN">如果 <code>x</code> 的所有元素也是 <code>y</code> 的元素,集合 <code>x</code> 是集合 <code>y</code><strong>子集</strong></p>
</div>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>strs = ["10", "0001", "111001", "1", "0"], m = 5, n = 3
<strong>输出:</strong>4
<strong>解释:</strong>最多有 5 个 0 和 3 个 1 的最大子集是 {"10","0001","1","0"} ,因此答案是 4 。
其他满足题意但较小的子集包括 {"0001","1"} 和 {"10","1","0"} 。{"111001"} 不满足题意,因为它含 4 个 1 ,大于 n 的值 3 。
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>strs = ["10", "0", "1"], m = 1, n = 1
<strong>输出:</strong>2
<strong>解释:</strong>最大的子集是 {"0", "1"} ,所以答案是 2 。
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= strs.length <= 600</code></li>
<li><code>1 <= strs[i].length <= 100</code></li>
<li><code>strs[i]</code> 仅由 <code>'0'</code> 和 <code>'1'</code> 组成</li>
<li><code>1 <= m, n <= 100</code></li>
</ul>
<div><div>Related Topics</div><div><li>动态规划</li></div></div>\n<div><li>👍 481</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long