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 987e9ff

Browse files
committed
"Distinct Subsequences"
1 parent d72cdeb commit 987e9ff

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

‎README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
185185
| 118 | [Pascal's Triangle] | [C](src/118.c) |
186186
| 117 | [Populating Next Right Pointers in Each Node II] | |
187187
| 116 | [Populating Next Right Pointers in Each Node] | [C](src/116.c) |
188-
| 115 | [Distinct Subsequences] | |
188+
| 115 | [Distinct Subsequences] | [C](src/115.c) |
189189
| 114 | [Flatten Binary Tree to Linked List] | [C](src/114.c) |
190190
| 113 | [Path Sum II] | [C++](src/113.cpp) |
191191
| 112 | [Path Sum] | [C](src/112.c) |

‎src/115.c

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <string.h>
4+
#include <assert.h>
5+
6+
int numDistinct(char* s, char* t) {
7+
if (s == NULL || t == NULL) return 0;
8+
int n = strlen(s);
9+
int m = strlen(t);
10+
11+
int (*dp)[n] = (int (*)[n])calloc(n * m, sizeof(int));
12+
int i, j;
13+
14+
dp[0][0] = (t[0] == s[0] ? 1 : 0);
15+
16+
for (j = 1; j < n; j++) {
17+
dp[0][j] = dp[0][j - 1] + (t[0] == s[j] ? 1 : 0);
18+
}
19+
20+
for (i = 1; i < m; i++) {
21+
dp[i][0] = 0;
22+
}
23+
24+
for (i = 1; i < m; i++) {
25+
for (j = 1; j < n; j++) {
26+
if (t[i] == s[j]) {
27+
dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1];
28+
}
29+
else {
30+
dp[i][j] = dp[i][j - 1];
31+
}
32+
}
33+
}
34+
35+
int ans = dp[m - 1][n - 1];
36+
free(dp);
37+
38+
return ans;
39+
}
40+
41+
int main() {
42+
char s[] = "acaaca";
43+
char t[] = "ca";
44+
45+
assert(numDistinct(s, t) == 4);
46+
47+
printf("all tests passed!\n");
48+
49+
return 0;
50+
}

0 commit comments

Comments
(0)

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