博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode] DP-- 474. Ones and Zeroes
阅读量:5047 次
发布时间:2019-06-12

本文共 1807 字,大约阅读时间需要 6 分钟。

 

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 = 3Output: 4Explanation: 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 = 1Output: 2Explanation: 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

你可能感兴趣的文章
bzoj 5252: [2018多省省队联测]林克卡特树
查看>>
Mybatis缓存
查看>>
使用mysql(6部曲)
查看>>
leetcode 217—Contains Duplicate
查看>>
Vue基础知识之组件及组件之间的数据传递(五)
查看>>
https 学习笔记三
查看>>
Biopython 安装使用
查看>>
20155228 2016-2017-2 《Java程序设计》第10周学习总结
查看>>
QT1.1-与Opencv的hello world
查看>>
无意间把你的个人资料当圣诞礼物,送给了网络犯罪份子吗?
查看>>
HDU 4920(杭电多校训练#5 1010 题) Matrix multiplication(不知道该挂个什么帽子。。。)...
查看>>
服务器端配置
查看>>
变态跳青蛙
查看>>
SVN版本控制服务
查看>>
Luogu P4342 Polygon 题解报告
查看>>
RHEL 6.5----iscsi多路径存储
查看>>
两侧跟随广告
查看>>
发生了 System.Data.SqlClient.SqlException HResult=0x80131904 Message=在与 SQL Server 建立连接时出现与网络相关的或特定...
查看>>
三种前端模块化规范
查看>>
三种隐藏元素方法的区别
查看>>