|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
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 |
| - */ |
13 |
| - |
14 | 3 | public class _115 {
|
15 |
| - public static class Solution1 { |
16 |
| - public int numDistinct(String s, String t) { |
17 |
| - int m = s.length(); |
18 |
| - int n = t.length(); |
19 |
| - int[][] dp = new int[m + 1][n + 1]; |
| 4 | + public static class Solution1 { |
| 5 | + public int numDistinct(String s, String t) { |
| 6 | + int m = s.length(); |
| 7 | + int n = t.length(); |
| 8 | + int[][] dp = new int[m + 1][n + 1]; |
20 | 9 |
|
21 |
| - char[] schar = s.toCharArray(); |
22 |
| - char[] tchar = t.toCharArray(); |
| 10 | + char[] schar = s.toCharArray(); |
| 11 | + char[] tchar = t.toCharArray(); |
23 | 12 |
|
24 |
| - for (int i = 0; i <= m; i++) { |
25 |
| - dp[i][0] = 1; |
26 |
| - } |
| 13 | + for (int i = 0; i <= m; i++) { |
| 14 | + dp[i][0] = 1; |
| 15 | + } |
27 | 16 |
|
28 |
| - for (int j = 1; j <= n; j++) { |
29 |
| - dp[0][j] = 0; |
30 |
| - } |
| 17 | + for (int j = 1; j <= n; j++) { |
| 18 | + dp[0][j] = 0; |
| 19 | + } |
31 | 20 |
|
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 |
| - } |
| 21 | + for (int i = 1; i <= m; i++) { |
| 22 | + for (int j = 1; j <= n; j++) { |
| 23 | + if (schar[i - 1] == tchar[j - 1]) { |
| 24 | + dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1]; |
| 25 | + } else { |
| 26 | + dp[i][j] = dp[i - 1][j]; |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + return dp[m][n]; |
39 | 31 | }
|
40 |
| - } |
41 |
| - return dp[m][n]; |
42 | 32 | }
|
43 |
| - } |
44 | 33 | }
|
0 commit comments