zoukankan      html  css  js  c++  java
  • [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]
     
  • 相关阅读:
    DExpose2:Windows 下窗体平铺预览
    第二章 随机变量及其分布3
    资源文件分享到QQ群共享里的方法
    第三章 多维随机变量及其分布1
    RegexBuddy
    第四章 随机变量的数字特征3
    html 表格排序
    关于微软自带的身份和角色验证
    学习中小型软件开发步骤
    学习路线图
  • 原文地址:https://www.cnblogs.com/anxin6699/p/7115603.html
Copyright © 2011-2022 走看看