跳到主要内容

Ones and Zeroes

描述

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 0, so the answer is 4.
Other valid but smaller subsets include 1 and 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 1, so the answer is 2.

Constraints:

  • 1strs.length6001 \leq strs.length \leq 600
  • 1strs[i].length1001 \leq strs[i].length \leq 100
  • strs[i] consists only of digits '0' and '1'.
  • 1m,n1001 \leq m, n \leq 100

分析

0-1 背包问题,每个字符串有两种重量,0 的个数和 1 的个数,每个字符串的价值都是 1,因此这个问题里有两个背包,一个装 0,一个装 1,价值则是背包里字符串的个数。

f(i,j,k)f(i, j, k)表示把前ii个字符串装进容量为jj的第一个背包和容量为kk第二个背包,可以获得的子集的最大大小,则状态转移方程是:

f(i,j,k)=max{f(i1,j,k),f(i1,jw0i,kw1i)+1}f(i,j,k)=\max\left\{f(i-1,j,k), f(i-1, j-w0_i,k-w1_i)+1\right\}

代码

# TODO