Java实现
class Solution {
public int findMaxForm(String[] strs, int m, int n) {
int[][] dp = new int[m + 1][n + 1];
for (String s : strs) {
int[] cnt = count(s);
for(int i = m;i>=cnt[0];i--){
for(int j = n;j>=cnt[1];j--){
dp[i][j] = Math.max(1+dp[i-cnt[0]][j-cnt[1]],dp[i][j]);
}
}
}
return dp[m][n];
}
public int[] count(String s) {
int[] c = new int[2];
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '0') {
c[0]++;
} else {
c[1]++;
}
}
return c;
}
}
C++实现
class Solution {
public:
int findMaxForm(vector<string>& strs, int m, int n) {
vector<vector<int> > dp(m+1,vector<int>(n+1,0));
for(int i = 0;i<strs.size();i++){
string s = strs[i];
vector<int> cnt = countOneAndZero(s);
for(int i = m;i>=cnt[0];i--){
for(int j = n; j>= cnt[1];j--){
dp[i][j] = max(dp[i-cnt[0]][j-cnt[1]]+1,dp[i][j]);
}
}
}
return dp[m][n];
}
vector<int> countOneAndZero(string s){
vector<int> cnt(2,0);
for(int i = 0;i<s.size();i++){
if(s[i]=='0'){
cnt[0]++;
}else{
cnt[1]++;
}
}
return cnt;
}
};