Skip to content

Commit 7d5e109

Browse files
authored
Create 474. Ones and Zeroes
1 parent 54a2274 commit 7d5e109

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Diff for: 474. Ones and Zeroes

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

0 commit comments

Comments
 (0)