Jeremiah_

474. Ones and Zeroes - LeetCode

Jul 4th, 2020
1,518
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<pair<int, int>> freq;
  4.     int max_idx;
  5.     int dp[700][120][120];
  6.    
  7.     int sol(int idx, int m, int n) {
  8.         if (idx == max_idx) return 0;
  9.        
  10.         if (dp[idx][m][n] != -1) return dp[idx][m][n];
  11.        
  12.         int ans = sol(idx+1, m, n);
  13.        
  14.         if (freq[idx].first <= m && freq[idx].second <= n) {
  15.             ans = max(ans, 1 + sol(idx+1, m-freq[idx].first, n-freq[idx].second));
  16.         }
  17.        
  18.         return dp[idx][m][n] = ans;
  19.        
  20.     }
  21.    
  22.     int findMaxForm(vector<string>& strs, int m, int n) {
  23.         max_idx = strs.size();
  24.         memset(dp, -1, sizeof dp);
  25.        
  26.         for (auto s : strs) {
  27.             int ones = 0;
  28.             int zeros = 0;
  29.             for (auto l : s) {
  30.                 if (l == '1') ones++;
  31.                 else zeros++;
  32.             }
  33.             freq.push_back(make_pair(zeros, ones));
  34.         }
  35.         return sol(0, m, n);
  36.     }
  37. };
Advertisement
Add Comment
Please, Sign In to add comment