Sponsored
Sponsored
This problem can be approached using a dynamic programming strategy similar to the knapsack problem. For each binary string, calculate the number of 0's and 1's it contains. Then, use a DP table to keep track of the maximum subset size you can achieve with a given count of 0's and 1's. We'll fill this table by iterating over each string and attempting to include it in our subset if the current capacity allows. Update the DP table in a reverse manner to avoid overwriting results prematurely.
Time Complexity: O(strsSize * m * n) where strsSize is the number of binary strings.
Space Complexity: O(m * n) for storing the DP table.
The Java solution employs an integer two-dimensional array to store the possible outcomes just like the C/C++ solutions. The core idea is preserved, where zeros and ones in each binary string are counted using Java's streaming API to make it concise. After computing the counts, the DP table is updated in a loop from back to front to ensure existing values are not overwritten.
The problem can also be tackled using a recursive function with memoization to store already computed results and avoid redundant calculations. This approach uses recursion to consider two choices for each string - either include it in the subset or not, based on the available capacity for zeros and ones. By storing intermediate results, we can significantly reduce the number of recursive calls needed, thus optimizing the process.
Time Complexity: O(strsSize * m * n) due to memoization.
Space Complexity: O(strsSize * m * n) for the memoization table.
1#include <string>
2#include <unordered_map>
3#include <vector>
4
5using namespace std;
6
7class Solution {
8 vector<string> strsLocal;
9 unordered_map<string, int> memo;
10
11 string getKey(int index, int m, int n) {
12 return to_string(index) + ',' + to_string(m) + ',' + to_string(n);
13 }
14
15 int helper(int index, int m, int n) {
16 if (index < 0) return 0;
17 string key = getKey(index, m, n);
18 if (memo.find(key) != memo.end()) {
19 return memo[key];
20 }
21 int zeros = count(strsLocal[index].begin(), strsLocal[index].end(), '0');
22 int ones = strsLocal[index].size() - zeros;
23 int exclude = helper(index - 1, m, n);
24 int include = 0;
25 if (m >= zeros && n >= ones) {
26 include = 1 + helper(index - 1, m - zeros, n - ones);
27 }
28 memo[key] = max(exclude, include);
29 return memo[key];
30 }
31public:
32 int findMaxForm(vector<string>& strs, int m, int n) {
33 strsLocal = strs;
34 memo.clear();
35 return helper(strs.size() - 1, m, n);
36 }
37};
In the C++ version, an unordered_map is used for memoization by storing states as strings. The memoization prevents repeated calculations, optimizing the recursive exploration of subsets. The recursive function considers all configurations and stores results to avoid recalculating for the same inputs.