Ones and Zeroes
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.
Example
Input: Array = {“10”, “0001”, “111001”, “1”, “0”}, m = 5, n = 3
Output: 4
Explanation: This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”
Solution
@DFS:超时,认识到必须在调用自身函数时改变变量才能回溯
class Solution:
def findMaxForm(self, strs, m, n):
"""
:type strs: List[str]
:type m: int
:type n: int
:rtype: int
"""
self.count = 0
self.generate(strs, 0, m, n, 0, [])
return self.count
def generate(self, strs, start, m, n, num, num_list):
if m<0 or n<0:
num-= 1
return
if num>self.count:
self.count = num
if m==0 and n==0:
return
for i in range(start, len(strs)):
num1 = strs[i].count('1')
num2 = strs[i].count('0')
self.generate(strs, i+1, m-num2, n-num1, num+1, num_list+[strs[i]])
@DP
class Solution:
def findMaxForm(self, strs, m, n):
"""
:type strs: List[str]
:type m: int
:type n: int
:rtype: int
"""
dp = [[0]*(n+1) for x in range(m+1)]
for str in strs:
zeros = str.count('0')
ones = str.count('1')
for i in range(m, zeros-1, -1):
for j in range(n, ones-1, -1):
dp[i][j] = max(dp[i-zeros][j-ones]+1, dp[i][j])
return dp[m][n]