Create 474. Ones and Zeroes.md

This commit is contained in:
ShusenTang 2019-12-16 22:29:38 +08:00 committed by GitHub
parent 00045095e1
commit 6ef0238053
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,35 @@
# [474. Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/)
# 思路
题目给定一个仅包含 0 和 1 字符串的数组。任务是从数组中选取尽可能多的字符串使这些字符串包含的0和1的数目分别不超过m和n。
我们把每个字符串看做是一件物品把字符串中0的数目和1的数目看做是两种“重量”所以就变成了一个二维01背包问题书包的两个限重分别是 m 和 n要求书包能装下的物品的最大数目也相当于价值最大设每个物品价值为1
关于背包问题系列的总结分析以及此题题解见[我的博客-动态规划之背包问题系列](https://tangshusen.me/2019/11/24/knapsack-problem/),这里不再详述,只给出代码。
# C++
``` C++
int findMaxForm(vector<string>& strs, int m, int n) {
int num = strs.size();
int w0, w1;
vector<vector<int>>dp(m+1, vector<int>(n+1, 0));
for(int i = 1; i <= num; i++){
w0 = 0; w1 = 0;
// 计算第i-1个字符串的两个重量
for(char &c: strs[i - 1]){
if(c == '0') w0 += 1;
else w1 += 1;
}
// 01背包, 逆向迭代更新dp
for(int j = m; j >= w0; j--)
for(int k = n; k >= w1; k--)
dp[j][k] = max(dp[j][k], 1+dp[j-w0][k-w1]);
}
return dp[m][n];
}
```