2020.10.12
原题:点击此处
考点:变形01背包
难点:经典01背包中只有1种背包,
本题中,背包有两种,一种装0,一种装1。
题解:
1、本题前提:构造一个函数,对一个01字符串,计算其0的数量以及1的数量,返回一个数组count【2】;
2、本题可以借助01背包的经典解决方法,创建三维数组。
【前i个字符串】【0的容量】【1的容量】
状态转移方程:
dp【k】【i】【j】 = dp【k-1】【i】【j】;
if(0的容量>count【0】 && 1的容量 > count【1】):
dp【k】【i】【j】 = Max(dp【k-1】【i】【j】, dp【k-1】【0的容量 - count【0】】【1的容量- count【1】】+ 1);
最终,dp数组右下角的值,即所求答案。
时间复杂度(mnl)
空间复杂度(mnl)
3、本题也可以通过空间压缩,
达到时间复杂度(mnl)
空间复杂度(mn)
设置dp【m+1】【n+1】
,如上述,一样代表0的容量和1的容量。
不同的是:
遍历数组不是从0到m,以及从0到n,而是从m到0,n到0。
这样做的目的,是防止后续字符串对上述DP数组进行操作时,将上一个字符串的记录进行覆盖,从而使答案出错。
``
if(0的容量>count【0】 && 1的容量 > count【1】):
dp【i】【j】 = Max(dp【i】【j】, dp【0的容量 - count【0】】【1的容量- count【1】】+ 1);
值得注意的是,如果是这样倒序打表的话,比上述的三维数组减少了一步 dp【k】【i】【j】 = dp【k-1】【i】【j】;
的赋值操作。
以下是本体的代码:
版本1
class Solution {
public int findMaxForm(String[] strs, int m, int n) {
int[][][] dp = new int[strs.length+1][m+1][n+1];
int[] count;
int max = 0;
//虚增一行0
for(int k = 1;k<strs.length+1;k++){
count = countZerosOnes(strs[k-1]);
for(int i = 0;i<m+1;i++){
for(int j=0;j<n+1;j++){
dp[k][i][j] = dp[k-1][i][j];
if(i>=count[0] && j>=count[1]){
//比较 不要以及要了之后的数量哪个更大。
dp[k][i][j] = Math.max(dp[k-1][i][j],dp[k-1][i-count[0]][j-count[1]]+1);
if(dp[k][i][j] > max){
max = dp[k][i][j];
}
}
}
}
}
return dp[strs.length][m][n];
}
//数0和1有多少个
public int[] countZerosOnes(String s){
int[] c = new int[2];
char[] ch = s.toCharArray();
for(int i=0; i<ch.length; i++){
if(ch[i] == '0'){
c[0] += 1;
}
if(ch[i] == '1'){
c[1] += 1;
}
}
return c;
}
}
版本2
class Solution {
public int findMaxForm(String[] strs, int m, int n) {
int[][] dp = new int[m+1][n+1];
int max = 0;
//从第一个字符开始数,一个一个装进背包
for(String s : strs){
int[] count = countZerosOnes(s);
for(int i = m; i>=0 ;i--){
for(int j = n;j>=0; j--){
if(i >= count[0] && j>= count[1]){
dp[i][j] = Math.max(dp[i-count[0]][j-count[1]]+1,dp[i][j]);
if(dp[i][j] > max){
max = dp[i][j];
}
}
}
}
}
return max;
}
//数0和1有多少个
public int[] countZerosOnes(String s){
int[] c = new int[2];
char[] ch = s.toCharArray();
for(int i=0; i<ch.length; i++){
if(ch[i] == '0'){
c[0] += 1;
}
if(ch[i] == '1'){
c[1] += 1;
}
}
return c;
}
}
出错记录:
1、max 一开始设置为了 -1;
(应该设置为0)
2、状态转移方程中缺少了Math.max()操作。