474. Ones and Zeroes
来源:互联网 发布:男士穿衣助手软件 编辑:程序博客网 时间:2024/06/05 20:39
474. Ones and Zeroes
- Total Accepted: 9812
- Total Submissions: 25753
- Difficulty: Medium
- Contributors:piy9
In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue.
For now, suppose you are a dominator of m 0s
and n 1s
respectively. On the other hand, there is an array with strings consisting of only 0s
and 1s
.
Now your task is to find the maximum number of strings that you can form with given m 0s
and n 1s
. Each 0
and 1
can be used at mostonce.
Note:
- The given numbers of
0s
and1s
will both not exceed100
- The size of given string array won't exceed
600
.
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".题目:给一个string的数组,并且给两个整数m和n,取一个string的组合,使得组合中0的个数为m,1的个数为n。找出一个组合,使其中的字符串个数最多。
提醒:这题的结果一定存在,就是说一定有符合 0s = m, 1s = n的组合,不需要考虑存在性。
这一题求的是最优结果,我们可以尝试使用动态规划。
我们另 f(a, b)为0的个数为a,1的个数为b的最优组合(字符串个数最多)
那么有递推式:
f(a, b) = max(f(a, b), f(a-i, b-j) + 1)
其中, i是其中一个字符串s中0的个数,j是s中1的个数。
这个递推式的意思就是,是在求f(a, b)时否选择字符串s加入组合中
代码如下:
int findMaxForm(vector<string>& strs, int m, int n) {
int f[m+3][n+3];
for (int i = 0; i <= m; i++)
for (int j = 0; j <= n; j++)
f[i][j] = 0; //全部初始化为0
for (string &s: strs){ //遍历vector
int one = 0, zero = 0;
for (char c: s)
if (c == '0') zero++;
else one++; //计算字符串s中0的个数和1的个数
for (int i = m; i >= zero; i--) //更新f二维数组,使其达到此时最优
for (int j = n; j >= one; j--) //如果i<zero或者j<one,则i-zero 和j-one为负数,不存在
f[i][j] = max(f[i][j], f[i-zero][j-one]+1);
}
return f[m][n];
}
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- 474. Ones and Zeroes
- Backpropagation
- Codeforces 591B Rebranding
- 洛谷 P1022 计算器的改良
- dubbo学习--Helloword
- C提高(1)
- 474. Ones and Zeroes
- Require模块入门三
- 零基础学贪心算法
- Everyone is an adaptive machine.
- 使用命令行查看mysql 数据库中的表
- 1283 最小周长
- 2017 计蒜之道 初赛 第六场
- +new Date()
- 容斥原理