leetcode刷题之旅——474. Ones and Zeroes
来源:互联网 发布:阿里云香港主机 编辑:程序博客网 时间:2024/05/19 11:48
这道题目是典型的二维背包问题,在动态规划中为middle,通过率35%的一道中级题目。
题目大意:
给定我们一个01字符串数组,然后给定我们固定的1的数量和0的数量。问的是我们最多可以用这些1和0,组成多少个字符串。固定的1和0的数目就是我们背包的体积,而每个字符串的价值都是1,而消耗的空间就是组成该字符串的1和0的数量,价值为都是1。
例子:
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".
算法:
使用二重背包问题的解决方法。对于每一个字符串,统计0和1的个数,作为其占去的体积。对于其价值来说,全部都是1,因为是统计能组成字符串的个数。其状态转移方程为:
for (int i=m; i>=zeros; i--) for (int j=n; j>=ones; j--) dp[i][j] = max(dp[i][j], dp[i-zeros][j-ones]+1);
代码:
class Solution {public: int findMaxForm(vector<string>& strs, int m, int n) { vector<vector<int>> dp(m+1,vector<int>(n+1,0)); for (auto &s: strs) { int ones = count(s.begin(), s.end(), '1'); int zeros= s.size()-ones; for (int i=m; i>=zeros; i--) for (int j=n; j>=ones; j--) dp[i][j] = max(dp[i][j], dp[i-zeros][j-ones]+1); } return dp[m][n]; }};
0 0
- 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
- [LeetCode] 474. Ones and Zeroes
- LeetCode: Ones and Zeroes
- [LeetCode] Ones and Zeroes
- Leetcode 474. Ones and Zeroes (Medium) (cpp)
- 第十一周:[Leetcode]474. Ones and Zeroes
- [Leetcode] 474. Ones and Zeroes 解题报告
- Oracle PlSql 问题集锦 - 数字或值错误:字符串缓冲区太小【ORA-06502】
- "此实现不是 Windows 平台 FIPS 验证的加密算法的一部分"解决办法
- Android 性能优化之使用线程池处理异步任务
- java集合中对象某属性比较排序Comparable与Comparator
- 用gradle打包android_apk时遇到的一些问题
- leetcode刷题之旅——474. Ones and Zeroes
- 超前进位加法器
- 关键字+静态+访问权限+内部类
- Framework7下拉刷新,滚动加载更多,幻灯片
- Android 通知
- Android 性能优化:使用 Lint 优化代码、去除多余资源
- Java 多线程编程基础
- 激活kail-linux系统控制台自动补全功能
- 开发的一些总结(2)