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]
     
  • 相关阅读:
    H-ui前端框架
    表单验证
    Switch 语句
    mysql下优化表和修复表命令使用说明(REPAIR TABLE和OPTIMIZE TABLE)
    mysql之repair table 修复表札记
    社会化海量数据采集爬虫框架搭建
    微信开发学习路线
    搜索引擎的商业价值
    centos7图形配置 firewall-config
    恢复gvim的ctl+v可视模式设置
  • 原文地址:https://www.cnblogs.com/anxin6699/p/7115603.html
Copyright © 2011-2022 走看看