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]
     
  • 相关阅读:
    JAVA的学习日记15
    JAVA的学习日记14
    CIRD主站与DOPAS构建笔记#1
    信仰之题——Codeforces Round 259(附题面完整翻译)
    平面最近点对问题
    BZOJ4552 [Tjoi2016&Heoi2016]排序
    BZOJ1001 [Beijing2006]狼抓兔子
    (二)k8s编写资源清单
    linux常用搜索工具find/whereis/locate
    解决centos7 的/etc/rc.local不会开机执行
  • 原文地址:https://www.cnblogs.com/anxin6699/p/7115603.html
Copyright © 2011-2022 走看看