# LC 474. Ones and Zeroes ### [Problem link](https://leetcode.com/problems/ones-and-zeroes/) ###### tags: `leedcode` `python` `c++` `medium` `DP` You are given an array of binary strings <code>strs</code> and two integers <code>m</code> and <code>n</code>. Return the size of the largest subset of <code>strs</code> such that there are **at most** <code>m</code> <code>0</code>'s and <code>n</code> <code>1</code>'s in the subset. A set <code>x</code> is a **subset** of a set <code>y</code> if all elements of <code>x</code> are also elements of <code>y</code>. **Example 1:** ``` Input: strs = ["10","0001","111001","1","0"], m = 5, n = 3 Output: 4 Explanation: The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4. Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}. {"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3. ``` **Example 2:** ``` Input: strs = ["10","0","1"], m = 1, n = 1 Output: 2 Explanation: The largest subset is {"0", "1"}, so the answer is 2. ``` **Constraints:** - <code>1 <= strs.length <= 600</code> - <code>1 <= strs[i].length <= 100</code> - <code>strs[i]</code> consists only of digits <code>'0'</code> and <code>'1'</code>. - <code>1 <= m, n <= 100</code> ## Solution 1 - DP #### Python ```python= class Solution: def findMaxForm(self, strs: List[str], m: int, n: int) -> int: dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)] for s in strs: ones = s.count('1') zeros = s.count('0') for i in range(m, zeros - 1, -1): for j in range(n, ones - 1, -1): dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1) return dp[-1][-1] ``` #### C++ ```cpp= class Solution { public: int findMaxForm(vector<string>& strs, int m, int n) { vector<vector<int>> dp(m + 1, vector<int>(n + 1 , 0)); for (string &str: strs) { int cnt0 = 0; int cnt1 = 0; for (char &c: str) { if (c == '0') { cnt0++; } else if (c == '1') { cnt1++; } } for (int i = m; i >= cnt0; i--) { for (int j = n; j >= cnt1; j--) { dp[i][j] = max(dp[i][j], dp[i - cnt0][j - cnt1] + 1); } } } return dp[m][n]; } }; ``` >### Complexity >k = strs.length >| | Time Complexity | Space Complexity | >| ----------- | --------------- | ---------------- | >| Solution 1 | O(kmn) | O(mn) | ## Note sol1: 先計算0與1的個數, 然後當作兩個維度的01背包.