题目

类型:动态规划
image.png

解题思路

代码

  1. class Solution {
  2. public int numDistinct(String s, String t) {
  3. memo = new int[s.length()][t.length()];
  4. for (int[] row : memo) {
  5. Arrays.fill(row, -1);
  6. }
  7. return dp(s, 0, t, 0);
  8. }
  9. int[][] memo;
  10. // 定义:该函数返回 s[i..] 中的子序列 t[j..] 的数量
  11. int dp(String s, int i, String t, int j) {
  12. int m = s.length(), n = t.length();
  13. if (j == n) {
  14. // 子序列全部匹配完成
  15. return 1;
  16. }
  17. if (n - j > m - i) {
  18. // 待匹配子序列的长度不应该比字符串的长度还要短
  19. return 0;
  20. }
  21. if (memo[i][j] != -1) {
  22. // 已经计算过对应状态
  23. return memo[i][j];
  24. }
  25. int res = 0;
  26. // 状态转移方程
  27. if (s.charAt(i) == t.charAt(j)) {
  28. res += dp(s, i + 1, t, j + 1) + dp(s, i + 1, t, j);
  29. } else {
  30. res += dp(s, i + 1, t, j);
  31. }
  32. memo[i][j] = res;
  33. return res;
  34. }
  35. }