|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| -public class _115 { |
4 |
| - /**This is a typical DP problem, illustrated in Jiuzhang. |
5 |
| - * |
6 |
| - * I've drawn out the 2d matrix on the whiteboard: |
7 |
| - * |
8 |
| - * 1. initialize a 2d matrix of size (m+1)*(n+1) |
9 |
| - * 2. initialize row 0, it should be 1,0,0,0,0... this is because when S is an empty string, only when T is empty, it could be a subsequence |
10 |
| - * 3. initialize column 0, it should be 1,1,1,1,1,1... |
11 |
| - * 4. starting from (1,1)*/ |
| 3 | +/** |
| 4 | + * 115. Distinct Subsequences |
| 5 | + * |
| 6 | + * Given a string S and a string T, count the number of distinct subsequences of S which equals T. A |
| 7 | + * subsequence of a string is a new string which is formed from the original string by deleting some |
| 8 | + * (can be none) of the characters without disturbing the relative positions of the remaining |
| 9 | + * characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). |
| 10 | + * |
| 11 | + * Here is an example: S = "rabbbit", T = "rabbit" Return 3. |
| 12 | + */ |
12 | 13 |
|
| 14 | +public class _115 { |
| 15 | + public static class Solution1 { |
13 | 16 | public int numDistinct(String s, String t) {
|
14 |
| - int m = s.length(); |
15 |
| - int n = t.length(); |
16 |
| - int[][] dp = new int[m + 1][n + 1]; |
| 17 | + int m = s.length(); |
| 18 | + int n = t.length(); |
| 19 | + int[][] dp = new int[m + 1][n + 1]; |
17 | 20 |
|
18 |
| - char[] schar = s.toCharArray(); |
19 |
| - char[] tchar = t.toCharArray(); |
| 21 | + char[] schar = s.toCharArray(); |
| 22 | + char[] tchar = t.toCharArray(); |
20 | 23 |
|
21 |
| - for (int i = 0; i <= m; i++) { |
22 |
| - dp[i][0] = 1; |
23 |
| - } |
| 24 | + for (int i = 0; i <= m; i++) { |
| 25 | + dp[i][0] = 1; |
| 26 | + } |
24 | 27 |
|
25 |
| - for (int j = 1; j <= n; j++) { |
26 |
| - dp[0][j] = 0; |
27 |
| - } |
| 28 | + for (int j = 1; j <= n; j++) { |
| 29 | + dp[0][j] = 0; |
| 30 | + } |
28 | 31 |
|
29 |
| - for (int i = 1; i <= m; i++) { |
30 |
| - for (int j = 1; j <= n; j++) { |
31 |
| - if (schar[i - 1] == tchar[j - 1]) { |
32 |
| - dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1]; |
33 |
| - } else { |
34 |
| - dp[i][j] = dp[i - 1][j]; |
35 |
| - } |
36 |
| - } |
| 32 | + for (int i = 1; i <= m; i++) { |
| 33 | + for (int j = 1; j <= n; j++) { |
| 34 | + if (schar[i - 1] == tchar[j - 1]) { |
| 35 | + dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1]; |
| 36 | + } else { |
| 37 | + dp[i][j] = dp[i - 1][j]; |
| 38 | + } |
37 | 39 | }
|
38 |
| - |
39 |
| - return dp[m][n]; |
| 40 | + } |
| 41 | + return dp[m][n]; |
40 | 42 | }
|
41 |
| - |
| 43 | + } |
42 | 44 | }
|
0 commit comments