nikunjsoni

474

Jun 11th, 2021
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int findMaxForm(vector<string>& strs, int m, int n) {
  4.         int dp[m+1][n+1];
  5.         memset(dp, 0, sizeof dp);
  6.        
  7.         // Knapsack DP.
  8.         // Here to reduce space from 3d to 2d, we have the loops iterating in reverse order.
  9.         for(auto s: strs){
  10.             vector<int> count = countZeroesOnes(s);
  11.             for(int zeroes=m; zeroes>=count[0]; zeroes--){
  12.                 for(int ones=n; ones>=count[1]; ones--){
  13.                     dp[zeroes][ones] = max(1+dp[zeroes-count[0]][ones-count[1]], dp[zeroes][ones]);
  14.                 }
  15.             }
  16.         }
  17.         return dp[m][n];
  18.     }
  19.    
  20.     vector<int> countZeroesOnes(string s){
  21.         vector<int> cnt(2,0);
  22.         for(int i=0; i<s.length(); i++){
  23.             if(s[i] == '0')
  24.                 cnt[0]++;
  25.             else
  26.                 cnt[1]++;
  27.         }
  28.         return cnt;
  29.     }
  30.    
  31. };
Advertisement
Add Comment
Please, Sign In to add comment