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 most once.
Note:
- The given numbers of
0s
and1s
will both not exceed100
- The size of given string array won't exceed
600
典型的动态规划的问题,dp[m][n]决定于前面的数组内容
开了dp的新类,慢慢研究
public class Solution {
public int findMaxForm(String[] strs, int m, int n) {
int[][] result = new int[m+1][n+1];
for(String s : strs){
int count[] = helper(s);
for(int i = m; i >= count[0]; i--){
for(int j = n; j >= count[1]; j--){
result[i][j] = Math.max(result[i][j], 1 + result[i - count[0]][j - count[1]]);
}
}
}
return result[m][n];
}
private int[] helper(String strs){
int[] count = new int[2];
for(int i = 0; i < strs.length(); i++){
if(strs.charAt(i) == '0'){
count[0]++;
}else{
count[1]++;
}
}
return count;
}
}