0474. Ones and Zeroes (M)
Ones and Zeroes (M)
题目
You are given an array of binary strings strs
and two integers m
and n
.
Return the size of the largest subset of strs
such that there are at most m
0
's and n
1
's in the subset.
A set x
is a subset of a set y
if all elements of x
are also elements of y
.
Example 1:
Input: strs = ["10","0001","111001","1","0"], m = 5, n = 3
Output: 4
Explanation: The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.
Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.
{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.
Example 2:
Input: strs = ["10","0","1"], m = 1, n = 1
Output: 2
Explanation: The largest subset is {"0", "1"}, so the answer is 2.
Constraints:
1 <= strs.length <= 600
1 <= strs[i].length <= 100
strs[i]
consists only of digits'0'
and'1'
.1 <= m, n <= 100
题意
给定一个包含仅由'0'和'1'组成的字符串的数组和整数m和n,要求选取最多的字符串,使其中的'0'个数不超过m,'1'个数不超过n。
思路
类似背包问题,使用动态规划解决。dp[i][j][k]表示在数组前i个中选出若干个字符串,使其中的'0'个数不超过j,'1'个数不超过k。对于第i个字符串,有两种情况,即选或者不选,记其中有zeros个'0',ones个'1',则可以得到递推式:
\[dp[i][j][k]=
\begin{cases}
dp[i-1][j][k], &j-zeros<0\ ||\ k-zeros<0\\
max(dp[i-1][j][k],dp[i-1][j-zeros][k-ones],&j-zeros>=0\ \&\&\ k-zeros>=0
\end{cases}
\]
可以使用滚动数组进行空间优化。
代码实现
Java
动态规划
class Solution {
public int findMaxForm(String[] strs, int m, int n) {
int[][][] dp = new int[strs.length + 1][m + 1][n + 1];
for (int i = 1; i <= strs.length; i++) {
int zeros = 0, ones = 0;
for (char c : strs[i - 1].toCharArray()) {
if (c == '0') zeros++;
else ones++;
}
for (int j = 0; j <= m; j++) {
for (int k = 0; k <= n; k++) {
if (j - zeros < 0 || k - ones < 0) dp[i][j][k] = dp[i - 1][j][k];
else dp[i][j][k] = Math.max(dp[i - 1][j][k], dp[i - 1][j - zeros][k - ones] + 1);
}
}
}
return dp[strs.length][m][n];
}
}
动态规划滚动数组优化
class Solution {
public int findMaxForm(String[] strs, int m, int n) {
int[][] dp = new int[m + 1][n + 1];
for (String str : strs) {
int zeros = 0, ones = 0;
for (char c : str.toCharArray()) {
if (c == '0') zeros++;
else ones++;
}
// 必须先从大端开始,防止重复计算
for (int i = m; i >= zeros; i--) {
for (int j = n; j >= ones; j--) {
dp[i][j] = Math.max(dp[i][j], dp[i - zeros][j - ones] + 1);
}
}
}
return dp[m][n];
}
}