mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 474. Ones and Zeroes.md
This commit is contained in:
parent
00045095e1
commit
6ef0238053
35
solutions/474. Ones and Zeroes.md
Normal file
35
solutions/474. Ones and Zeroes.md
Normal 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];
|
||||
}
|
||||
```
|
Loading…
Reference in New Issue
Block a user