Question
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.
假设你分别控制着m个0和n个1.另外,这儿有一个仅包含0和1的字符串的列表。现在你的任务是通过给你的m个0和1个n找到最大数量的字符串,每个0和1只能使用一次
Example
Input: Array = {“10”, “0001”, “111001”, “1”, “0”}, m = 5, n = 3
Output: 4Explanation: This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”
Input: Array = {“10”, “0”, “1”}, m = 1, n = 1
Output: 2Explanation: You could form “10”, but then you’d have nothing left. Better form “0” and “1”.
Solution
动态规划解。其实这道题和Target Sum的解法差不多,我们的目的都是将任意个列表中的元素相加能够得到target,在target Sum中我们是需要找到有多少种方法,所以设dp[i]为组合成i的方法数,在这里我们是需要有最多的字符串数,那么我们就定义dp[i][j]:列表中的字符串组合成i个0,j个1时的最多字符串数。对于这种每个元素只能使用的情况,我们都需要每次加入一个字符串s(假设有i个0,j个1),然后更新dp[i:m][j:n],直到每个元素都加进来。递归式:dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1)。每次新加入一个字符串,都取字符串多的情况即可
class Solution(object): def findMaxForm(self, strs, m, n): """ :type strs: List[str] :type m: int :type n: int :rtype: int """ dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)] for s in strs: zeros, ones = s.count('0'), s.count('1') # 更新dp[i:m][j:n] for z in range(m, zeros - 1, -1): for o in range(n, ones - 1, -1): dp[z][o] = max(dp[z][o], dp[z - zeros][o - ones] + 1) return dp[m][n]