-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy path474. Ones and Zeroes
72 lines (56 loc) · 1.75 KB
/
474. Ones and Zeroes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class Solution {
int[][][] dp;
public int findMaxForm(String[] strs, int m, int n) {
dp= new int[m+1][n+1][strs.length];
return helper(strs,m,n,0);
}
int helper(String[] strs,int zero,int one,int index){
if(index==strs.length || zero + one == 0){
return 0;
}
if(dp[zero][one][index]>0){
return dp[zero][one][index];
}
int[] count = count(strs[index]);
//consider changes the zero ad one
int consider=0;
if(zero >=count[0] && one>=count[1]){
consider = 1 + helper(strs,zero-count[0],one-count[1],index+1);
}
int skip = helper(strs,zero,one,index+1);
//skip
dp[zero][one][index]=Math.max(consider,skip);;
return dp[zero][one][index];
}
int[] count(String s){
int[] count=new int[2];
for(char c: s.toCharArray()){
count[c-'0']++;
}
return count;
}
}
class Solution {
int[][] dp;
public int findMaxForm(String[] strs, int m, int n) {
dp= new int[m+1][n+1];
for(String s:strs){
int[] count = count(s);
//zero m-count[0] ---- 0
//one n - count[1] ---- 0
for(int zero=m;zero>=count[0];zero--){
for(int one=n; one>=count[1]; one--){
dp[zero][one] = Math.max(dp[zero-count[0]][one-count[1]] +1 , dp[zero][one]);
}
}
}
return dp[m][n];
}
int[] count(String s){
int[] count=new int[2];
for(char c: s.toCharArray()){
count[c-'0']++;
}
return count;
}
}