You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/1900-1999/1980.Find Unique Binary String/README_EN.md
+24-1
Original file line number
Diff line number
Diff line change
@@ -46,7 +46,15 @@
46
46
47
47
## Solutions
48
48
49
-
### Solution 1
49
+
### Solution 1: Counting + Enumeration
50
+
51
+
Since the number of occurrences of '1' in a binary string of length $n$ can be $0, 1, 2, \cdots, n$ (there are $n + 1$ possibilities), we can certainly find a new binary string that has a different number of '1's from every string in `nums`.
52
+
53
+
We can use an integer $mask$ to record the occurrence of '1' in all strings, i.e., the $i$-th bit of $mask$ is $1$ indicates that there is a string of length $n$ in which '1' appears $i$ times, otherwise it does not exist.
54
+
55
+
Then we start to enumerate the number of times '1' appears in a binary string of length $n$ from $0$. If the $i$-th bit of $mask$ is $0$, it means that there is no string of length $n$ in which '1' appears $i$ times. We can return this string as the answer.
56
+
57
+
The time complexity is $O(L)$, where $L$ is the total length of the strings in `nums`. The space complexity is $O(1)$.
Let $f[i][j]$ represent whether it is possible to select elements from the first $i$ rows with a sum of $j$. Then we have the state transition equation:
67
+
68
+
$$
69
+
f[i][j] = \begin{cases} 1 & \text{if there exists } x \in row[i] \text{ such that } f[i - 1][j - x] = 1 \\ 0 & \text{otherwise} \end{cases}
70
+
$$
71
+
72
+
where $row[i]$ represents the set of elements in the $i$-th row.
73
+
74
+
Since $f[i][j]$ is only related to $f[i - 1][j]$, we can use a rolling array to optimize the space complexity.
75
+
76
+
Finally, we traverse the $f$ array to find the smallest absolute difference.
77
+
78
+
The time complexity is $O(m^2 \times n \times C)$ and the space complexity is $O(m \times C)$. Here, $m$ and $n$ are the number of rows and columns of the matrix, respectively, and $C$ is the maximum value of the matrix elements.
0 commit comments