Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5798d7b

Browse files
committed
Add C++ solutions for leetcode 474.
1 parent d218fdd commit 5798d7b

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include<vector>
2+
#include<algorithm>
3+
#include<iostream>
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
int findMaxForm(vector<string>& strs, int m, int n) {
9+
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
10+
for (string& str : strs)
11+
{
12+
int zeros = 0, ones = 0;
13+
for (char& ch : str)
14+
{
15+
if (ch == '0')
16+
zeros++;
17+
else ones++;
18+
}
19+
for (int i = m; i >= zeros; i--) /* 设置好边界: 数组不会越界, 同时当超过字符0、1的数量超过其容量m, n时, 更新dp数组时不考虑它们, 它们对dp表不会有任何影响。 */
20+
{
21+
for (int j = n; j >= ones; j--)
22+
dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1);
23+
}
24+
}
25+
return dp[m][n];
26+
}
27+
};
28+
29+
// Test
30+
int main()
31+
{
32+
Solution sol;
33+
vector<string> strs = {"10", "0001", "111001", "1", "0"};
34+
int m = 5;
35+
int n = 3;
36+
auto res = sol.findMaxForm(strs, m, n);
37+
cout << res << endl;
38+
39+
return 0;
40+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include<vector>
2+
#include<algorithm>
3+
#include<iostream>
4+
using namespace std;
5+
6+
class Solution {
7+
public:
8+
int findMaxForm(vector<string>& strs, int m, int n) {
9+
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
10+
auto newDp = dp;
11+
for (string& str : strs)
12+
{
13+
int zeros = 0, ones = 0;
14+
for (char& ch : str)
15+
{
16+
if (ch == '0')
17+
zeros++;
18+
else ones++;
19+
}
20+
for (int i = zeros; i <= m; i++)
21+
{
22+
for (int j = ones; j <= n; j++)
23+
newDp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1);
24+
}
25+
dp = newDp; // 更新一下供下一次迭代使用
26+
}
27+
return newDp[m][n];
28+
}
29+
};
30+
31+
// Test
32+
int main()
33+
{
34+
Solution sol;
35+
vector<string> strs = {"10", "0001", "111001", "1", "0"};
36+
int m = 5;
37+
int n = 3;
38+
auto res = sol.findMaxForm(strs, m, n);
39+
cout << res << endl;
40+
41+
return 0;
42+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /