Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 12ceede

Browse files
snowanazl397985856
authored andcommitted
feat: add LC 474 ones and zeros english version solutions (azl397985856#143)
1 parent 270c760 commit 12ceede

File tree

3 files changed

+300
-0
lines changed

3 files changed

+300
-0
lines changed

‎README.en.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,7 @@ The data structures mainly includes:
200200
- [0416.partition-equal-subset-sum](./problems/416.partition-equal-subset-sum.md)
201201
- [0445.add-two-numbers-ii](./problems/445.add-two-numbers-ii.md)
202202
- [0454.4-sum-ii](./problems/454.4-sum-ii.md)
203+
- [0474.ones-and-zeros](./problems/474.ones-and-zeros-en.md) 🆕
203204
- [0494.target-sum](./problems/494.target-sum.md)
204205
- [0516.longest-palindromic-subsequence](./problems/516.longest-palindromic-subsequence.md)
205206
- [0518.coin-change-2](./problems/518.coin-change-2.md)
623 KB
Loading[フレーム]

‎problems/474.ones-and-zeros-en.md‎

Lines changed: 299 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,299 @@
1+
## Problem
2+
https://leetcode.com/problems/ones-and-zeroes/
3+
4+
## Problem Description
5+
```
6+
In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue.
7+
8+
For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s.
9+
10+
Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. Each 0 and 1 can be used at most once.
11+
12+
Note:
13+
14+
The given numbers of 0s and 1s will both not exceed 100
15+
The size of given string array won't exceed 600.
16+
17+
Example 1:
18+
19+
Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3
20+
Output: 4
21+
22+
Explanation: This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are "10,"0001","1","0"
23+
24+
Example 2:
25+
26+
Input: Array = {"10", "0", "1"}, m = 1, n = 1
27+
Output: 2
28+
29+
Explanation: You could form "10", but then you'd have nothing left. Better form "0" and "1".
30+
```
31+
32+
33+
## Solution
34+
35+
When see the requirement of returning maximum number, length etc, and not require to list all possible value. Usually it can
36+
be solved by DP.
37+
38+
This problem we can see is a `0-1 backpack` issue, either take current string or not take current string.
39+
40+
And during interview, DP problem is hard to come up with immediately, recommend starting from Brute force, then optimize the solution step by step, until interviewer is happy, :-)
41+
42+
Below give 4 solutions based on complexities analysis.
43+
44+
#### Solution #1 - Brute Force (Recursively)
45+
46+
Brute force solution is to calculate all possible subsets. Then count `0s` and `1s` for each subset, use global variable `max` to keep track of maximum number.
47+
if `count(0) <= m && count(1) <= n;`, then current string can be taken into counts.
48+
49+
for `strs` length `len`, total subsets are `2^len`, Time Complexity is too high in this solution.
50+
51+
#### Complexity Analysis
52+
- *Time Complexity:* `O(2^len * s) - len is Strs length, s is the average string length `
53+
- *Space Complexity:* `O(1)`
54+
55+
#### Solution #2 - Memorization + Recursive
56+
In Solution #1, brute force, we used recursive to calculate all subsets, in reality, many cases are duplicate, so that we can use
57+
memorization to record those subsets which realdy been calculated, avoid dup calculation. Use a memo array, if already calculated,
58+
then return memo value, otherwise, set the max value into memo.
59+
60+
`memo[i][j][k] - maximum number of strings can be formed by j 0s and k 1s in range [0, i] strings`
61+
62+
`helper(strs, i, j, k, memo)` recursively:
63+
1. if `memo[i][j][k] != 0`, meaning already checked for j 0s and k 1s case, return value.
64+
2. if not checked, then check condition `count0 <= j && count1 <= k`,
65+
a. if true,take current strings `strs[i]`, so` 0s -> j-count0`, and `1s -> k-count1`,
66+
check next string `helper(strs, i+1, j-count0, k-count1, memo)`
67+
3. not take current string `strs[i]`, check next string `helper(strs, i+1, j, k, memo)`
68+
4. save max value into`memo[i][j][k]`
69+
5. recursively
70+
71+
#### Complexity Analysis
72+
- *Time Complexity:* `O(l * m * n) - l is length of strs, m is number of 0s, n is number of 1s`
73+
- *Space Complexity:* `O(l * m * n) - memo 3D Array`
74+
75+
#### Solution #3 - 3D DP
76+
In Solution #2, used memorization + recursive, this Solution use 3D DP to represent iterative way
77+
78+
`dp[i][j][k] - the maximum number of strings can be formed using j 0s and k 1s in range [0, i] strings`
79+
80+
DP Formula:
81+
`dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j - count0][k - count1])` - `count0 - number of 0s in strs[i]` and `count1 - number of 1s in strs[i]`
82+
83+
compare `j` and `count0`, `k` and `count1`, based on taking current string or not, DP formula as below:
84+
- `j >= count0 && k >= count1`,
85+
86+
`dp[i][j][k] = max(dp[i - 1][j][k], dp[i - 1][j - count0][k - count1] + 1)`
87+
88+
- not meet condition, not take current string
89+
90+
`dp[i][j][k] = dp[i - 1][j][k]`
91+
92+
`dp[l][m][n]` is result.
93+
94+
#### Complexity Analysis
95+
- *Time Complexity:* `O(l * m * n) - l is strs length, m is number of 0s, n is number of 1s`
96+
- *Space Complexity:* `O(l * m * n) - dp 3D array`
97+
98+
#### Solution #4 - 2D DP
99+
100+
In Solution #3, we kept track all state value, but we only need previous state, so we can reduce 3 dimention to 2 dimention array,
101+
here we use `dp[2][m][n]`, rotate track previous and current values. Further observation, we notice that first row (track previous state),
102+
we don't need the whole row values, we only care about 2 position value: `dp[i - 1][j][k]` and `dp[i - 1][j - count0][k - count1]`.
103+
so it can be reduced to 2D array. `dp[m][n]`.
104+
105+
2D DP definition:
106+
107+
`dp[m+1][n+1] - maximum counts, m is number of 0, n is number of 1`
108+
109+
DP formula:
110+
111+
`dp[i][j] = max(dp[i][j], dp[i - count0][j - count1] + 1)`
112+
113+
For example:
114+
115+
![ones and zeros 2d dp](../assets/problems/474.ones-and-zeros-2d-dp.png)
116+
117+
####
118+
- *Time Complexity:* `O(l * m * n) - l is strs length,m is number of 0,n number of 1`
119+
- *Space Complexity:* `O(m * n) - dp 2D array`
120+
121+
## Key Points Analysis
122+
123+
## Code (`Java/Python3`)
124+
#### Solution #1 - Recursive (TLE)
125+
*Java code*
126+
```java
127+
class OnesAndZerosBFRecursive {
128+
public int findMaxForm2(String[] strs, int m, int n) {
129+
return helper(strs, 0, m, n);
130+
}
131+
private int helper(String[] strs, int idx, int j, int k) {
132+
if (idx == strs.length) return 0;
133+
// count current idx string number of zeros and ones
134+
int[] counts = countZeroOnes(strs[idx]);
135+
// if j >= count0 && k >= count1, take current index string
136+
int takeCurrStr = j - counts[0] >= 0 && k - counts[1] >= 0
137+
? 1 + helper(strs, idx + 1, j - counts[0], k - counts[1])
138+
: -1;
139+
// don't take current index string strs[idx], continue next string
140+
int notTakeCurrStr = helper(strs, idx + 1, j, k);
141+
return Math.max(takeCurrStr, notTakeCurrStr);
142+
}
143+
private int[] countZeroOnes(String s) {
144+
int[] res = new int[2];
145+
for (char ch : s.toCharArray()) {
146+
res[ch - '0']++;
147+
}
148+
return res;
149+
}
150+
}
151+
```
152+
153+
*Python3 code*
154+
```python
155+
class Solution:
156+
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
157+
return self.helper(strs, m, n, 0)
158+
159+
def helper(self, strs, m, n, idx):
160+
if idx == len(strs):
161+
return 0
162+
take_curr_str = -1
163+
count0, count1 = strs[idx].count('0'), strs[idx].count('1')
164+
if m >= count0 and n >= count1:
165+
take_curr_str = max(take_curr_str, self.helper(strs, m - count0, n - count1, idx + 1) + 1)
166+
not_take_curr_str = self.helper(strs, m, n, idx + 1)
167+
return max(take_curr_str, not_take_curr_str)
168+
169+
```
170+
171+
#### Solution #2 - Memorization + Recursive
172+
*Java code*
173+
```java
174+
class OnesAndZerosMemoRecur {
175+
public int findMaxForm4(String[] strs, int m, int n) {
176+
return helper(strs, 0, m, n, new int[strs.length][m + 1][n + 1]);
177+
}
178+
private int helper(String[] strs, int idx, int j, int k, int[][][] memo) {
179+
if (idx == strs.length) return 0;
180+
// check if already calculated, return value
181+
if (memo[idx][j][k] != 0) {
182+
return memo[idx][j][k];
183+
}
184+
int[] counts = countZeroOnes(strs[idx]);
185+
// if satisfy condition, take current string, strs[idx], update count0 and count1
186+
int takeCurrStr = j - counts[0] >= 0 && k - counts[1] >= 0
187+
? 1 + helper(strs, idx + 1, j - counts[0], k - counts[1], memo)
188+
: -1;
189+
// not take current string
190+
int notTakeCurrStr = helper(strs, idx + 1, j, k, memo);
191+
// always keep track the max value into memory
192+
memo[idx][j][k] = Math.max(takeCurrStr, notTakeCurrStr);
193+
return memo[idx][j][k];
194+
}
195+
private int[] countZeroOnes(String s) {
196+
int[] res = new int[2];
197+
for (char ch : s.toCharArray()) {
198+
res[ch - '0']++;
199+
}
200+
return res;
201+
}
202+
}
203+
```
204+
205+
*Python3 code* - (TLE)
206+
```python
207+
class Solution:
208+
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
209+
memo = {k:[[0]*(n+1) for _ in range(m+1)] for k in range(len(strs)+1)}
210+
return self.helper(strs, 0, m, n, memo)
211+
212+
def helper(self, strs, idx, m, n, memo):
213+
if idx == len(strs):
214+
return 0
215+
if memo[idx][m][n] != 0:
216+
return memo[idx][m][n]
217+
take_curr_str = -1
218+
count0, count1 = strs[idx].count('0'), strs[idx].count('1')
219+
if m >= count0 and n >= count1:
220+
take_curr_str = max(take_curr_str, self.helper(strs, idx + 1, m - count0, n - count1, memo) + 1)
221+
not_take_curr_str = self.helper(strs, idx + 1, m, n, memo)
222+
memo[idx][m][n] = max(take_curr_str, not_take_curr_str)
223+
return memo[idx][m][n]
224+
```
225+
226+
227+
#### Solution #3 - 3D DP
228+
*Java code*
229+
```java
230+
class OnesAndZeros3DDP {
231+
public int findMaxForm(String[] strs, int m, int n) {
232+
int l = strs.length;
233+
int [][][] d = new int[l + 1][m + 1][n + 1];
234+
for (int i = 0; i <= l; i ++){
235+
int [] nums = new int[]{0,0};
236+
if (i > 0){
237+
nums = countZeroOnes(strs[i - 1]);
238+
}
239+
for (int j = 0; j <= m; j ++){
240+
for (int k = 0; k <= n; k ++){
241+
if (i == 0) {
242+
d[i][j][k] = 0;
243+
} else if (j >= nums[0] && k >= nums[1]){
244+
d[i][j][k] = Math.max(d[i - 1][j][k], d[i - 1][j - nums[0]][k - nums[1]] + 1);
245+
} else {
246+
d[i][j][k] = d[i - 1][j][k];
247+
}
248+
}
249+
}
250+
}
251+
return d[l][m][n];
252+
}
253+
}
254+
```
255+
#### Solution #4 - 2D DP
256+
*Java code*
257+
```java
258+
class OnesAndZeros2DDP {
259+
public int findMaxForm(String[] strs, int m, int n) {
260+
int[][] dp = new int[m + 1][n + 1];
261+
for (String s : strs) {
262+
int[] counts = countZeroOnes(s);
263+
for (int i = m; i >= counts[0]; i--) {
264+
for (int j = n; j >= counts[1]; j--) {
265+
dp[i][j] = Math.max(1 + dp[i - counts[0]][j - counts[1]], dp[i][j]);
266+
}
267+
}
268+
}
269+
return dp[m][n];
270+
}
271+
private int[] countZeroOnes(String s) {
272+
int[] res = new int[2];
273+
for (char ch : s.toCharArray()) {
274+
res[ch - '0']++;
275+
}
276+
return res;
277+
}
278+
}
279+
280+
```
281+
*Python3 code*
282+
```python
283+
class Solution:
284+
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
285+
l = len(strs)
286+
dp = [[0]*(n+1) for _ in range(m+1)]
287+
for i in range(1, l + 1):
288+
count0, count1 = strs[i - 1].count('0'), strs[i - 1].count('1')
289+
for i in reversed(range(count0, m + 1)):
290+
for j in reversed(range(count1, n + 1)):
291+
dp[i][j] = max(dp[i][j], 1 + dp[i - count0][j - count1])
292+
return dp[m][n]
293+
```
294+
295+
## Similar problems
296+
297+
- [Leetcode 600. Non-negative Integers without Consecutive Ones](https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/)
298+
- [Leetcode 322. Coin Change](https://leetcode.com/problems/coin-change/)
299+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /