[Leetcode] DP-- 474. 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.

Note:

  1. The given numbers of 0s and 1s will both not exceed 100
  2. The size of given string array won't exceed 600.

Example 1:

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”

Example 2:

Input: Array = {"10", "0", "1"}, m = 1, n = 1
Output: 2

Explanation: You could form "10", but then you'd have nothing left. Better form "0" and "1".

Solution:

 1. 1st naive method two layer iterations of every element in the array

   for i to n:  

        for j to n:          

            judge the element can be formed m zeros and n ones          

           and then decrease m and n

2. 2nd use DP

   (1) Define the subproblem
       DP[i][j] represents the maximum number represented with i zeros and j ones
   (2) Find the recursion
         state function:    dp[i][j] = max(dp[i][j],  1 + dp[i-zeros][j-ones])
   (3) Get the base case
         initialize dp[i][j] = 0       
 
   
 1    dp = [[0] *(n+1) for _ in range(m+1)]
 2         
 3         #print ("ttt: ",dp)
 4         for s in strs:
 5             dic = Counter(s)
 6             zeros = dic["0"]
 7             ones = dic["1"]
 8 
 9             for i in range(m, zeros-1, -1):
10                 for j in range(n, ones-1, -1):
11                     dp[i][j] = max(dp[i][j],  1 + dp[i-zeros][j-ones])
12                     #print ("ddd: ", i, j, dp[i][j])
13         return dp[m][n]
 
原文地址:https://www.cnblogs.com/anxin6699/p/7115603.html