LeetCode/solutions/474. Ones and Zeroes.md
2019-12-16 22:29:38 +08:00

36 lines
1.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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];
}
```