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 5196ad9

Browse files
committed
Time: 39 ms (65.11%), Space: 12.2 MB (98.56%) - LeetHub
1 parent 8718f71 commit 5196ad9

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*dp[i][j] denote the number of distinct subsequences starting with 'i' and end with 'j'
2+
Here's the dp transition:
3+
Case '0':
4+
If the current character is '0', since we are counting distinct subsequences and there shouldn't be any leading zeros in the subsequences, we set dp[0][0] = 1, ex: string "000000" only have a subsequence '0'
5+
dp[1][0] = dp[1][0] + dp[1][1] because it will be the number of ways that we add a '0' to a subsequence starting with '1' and ends with either '0' or '1'
6+
7+
Case '1':
8+
If the current character is '1', since we can't have leading zeros, dp[0][1] is always 0 ("0001" is not a valid subsequence)
9+
The transition will be dp[1][1] = dp[1][0] + dp[1][1] + 1. As we can see, dp[1][0] + dp[1][1] part is same as the case ending with zero. Since we append a '1' to every subsequence dp[1][0] and dp[1][1], we are missing the subsequence "1" with length 1; therefore, we add a one to it.
10+
11+
Note that all calculation above should be done with modulo.
12+
13+
Time Complexity: O(n)
14+
Space Complexity: O(1)
15+
*/
16+
typedef int64_t ll;
17+
18+
class Solution {
19+
public:
20+
int numberOfUniqueGoodSubsequences(string s) {
21+
const int mod = 1e9 + 7;
22+
ll dp[2][2] = {};
23+
for(char c : s) {
24+
int a = c - '0';
25+
if(a == 0) {
26+
dp[0][0] = 1;
27+
dp[1][0] = (dp[1][0] + dp[1][1]) % mod;
28+
} else {
29+
dp[1][1] = (dp[1][0] + dp[1][1] + 1) % mod;
30+
}
31+
}
32+
return (dp[0][0] + dp[0][1] + dp[1][0] + dp[1][1]) % mod;
33+
}
34+
};

0 commit comments

Comments
(0)

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