Leetcode-474-Ones and Zeroes
来源:互联网 发布:ubuntu ctrl alt l 编辑:程序博客网 时间:2024/06/05 19:02
474. Ones and Zeroes
动态规划……每次必坑……看这道题目,和0-1背包问题有点儿像
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:
The given numbers of 0s and 1s will both not exceed 100The size of given string array won't exceed 600.
Example 1
Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3Output: 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”
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".
题目的意思简单来说就是,给了一些0和1,以及一些字符串,用这些0和1来组成这些字符串,每个01都只能用一次,求最多能组成多少个字符串,(这些字符串每个只能被组成一次)。
动态规划的套路就是,每次必须想到一个规律,我个人的理解是,这个规律可以通过小范围内的最优解得到大范围的解,类似于知道dp[i],就能得到dp[i+1]=max{dp[i], ... ,...)
然而我每次都找不到。。。
同样的,这次也是通过别人的代码,真气耗尽才想明白。参考链接https://discuss.leetcode.com/topic/71438/c-dp-solution-with-comments
设置二维数组dp[][],dp[j][k]表示当使用了j个0和k个1时,所能组成的最多的字符串个数。初始dp[][]都为0.
每遍历一个字符串,计算该字符串中的0和1的个数,记录为n0和n1。
若当前字符串可以被构造,那么dp[j][k]为不加n0个0和n1个1之前的位置的个数+1.即dp[j][k]=dp[j-n0][k-n1]+1。若dp[j][k]原来的值大于更新后的这个值,则不需要更新。
该迭代要从矩阵的右下角向左上角方向计算,若从左上角开始计算,会产生重复的计算,举例一试便知。
上代码~
class Solution {public: int findMaxForm(vector<string>& strs, int m, int n) { int length = strs.size(),n0,n1; vector<vector<int>> dp (m+1,vector<int> (n+1,0)); for(int i = 1; i <= length; i ++){ n0 = 0; n1 = 0; for(auto c:strs[i-1]){ if(c == '0') n0++; else n1++; } for(int j = m; j >= 0; j --){ for(int k = n; k >= 0; k --){ if(n0<=j && n1<=k){ dp[j][k] = max(dp[j][k], dp[j-n0][k-n1]+1); } } } } return dp[m][n]; }};
- Leetcode-474-Ones and Zeroes
- LeetCode 474 Ones and Zeroes
- Leetcode 474 Ones and Zeroes
- Leetcode 474 Ones and Zeroes
- LeetCode: Ones and Zeroes
- [LeetCode] Ones and Zeroes
- LeetCode 474 Ones and Zeroes 题解
- LeetCode 474. Ones and Zeroes
- [leetcode] 474. Ones and Zeroes
- LeetCode 474. Ones and Zeroes
- Leetcode-474. Ones and Zeroes
- [LeetCode]474. Ones and Zeroes
- 【LeetCode】 474. Ones and Zeroes
- LeetCode 474. Ones and Zeroes
- [leetcode]474. Ones and Zeroes
- Leetcode 474. Ones and Zeroes
- Leetcode 474. Ones and Zeroes
- leetcode 474. Ones and Zeroes
- 关于拷贝构造函数的调用方式
- 面试题sizeof和五大内存分区
- android 微信分享带有缩略图的网页
- Android全局异常捕获日志打印
- csdn如何装载别人的博客
- Leetcode-474-Ones and Zeroes
- 软件测试误区
- POJ 2125 Destroying The Graph 二分图 最小点权覆盖
- Linux学习笔记4 (磁盘管理)
- PL/SQL 学习-NVL函数
- Android 6.0 开机时间分析工具bootchart的使用
- mt7601驱动加载
- Android之轻量数据库SQLite
- Enterprise Architect支持的各种图