LeetCode 115. Distinct Subsequences

原题链接在这里:https://leetcode.com/problems/distinct-subsequences/

题目:

Given a string S and a string T, count the number of distinct subsequences of S which equals T.

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).

Example 1:

Input: S = "rabbbit", T = "rabbit"
Output: 3
Explanation:

As shown below, there are 3 ways you can generate "rabbit" from S.
(The caret symbol ^ means the chosen letters)

rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^

Example 2:

Input: S = "babgbag", T = "bag"
Output: 5
Explanation:

As shown below, there are 5 ways you can generate "bag" from S.
(The caret symbol ^ means the chosen letters)

babgbag
^^ ^
babgbag
^^    ^
babgbag
^    ^^
babgbag
  ^  ^^
babgbag
    ^^^

题解:

Let dp[i,j]表示s[0....i]有多少种方法可以减成t[0.......j].

If s.charAt(i-1) == t.charAt(j-1),

dp[i][j] = dp[i-1][j-1] (用上最新的match, 之前s[0....i-1]减到t[0...j-1]的方法都用最后一个match, 所以总共的方法数不变)  + dp[i-1][j] (不用当前match, 之前s[0...i-1]减到t[0...j]的方法即可).

s.charAt(i-1) != t.charAt(j-1),

不match的话只能是之前s[0...i-1]减到t[0...j]的方法.

Time Complexity: O(m*n).m = s.length().n = t.length().

Space:O(m*n).

AC Java:

 1 class Solution {
 2     public int numDistinct(String s, String t) {
 3         int m = s.length();
 4         int n = t.length();
 5         int [][] dp = new int[m+1][n+1];
 6         for(int i = 0; i<=m; i++){
 7             dp[i][0] = 1;
 8         }
 9         
10         for(int i = 1; i<=m; i++){
11             for(int j = 1; j<=n; j++){
12                 if(s.charAt(i-1) == t.charAt(j-1)){
13                     dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
14                 }else{
15                     dp[i][j] = dp[i-1][j];
16                 }
17             }
18         }
19         
20         return dp[m][n];
21     }
22 }

类似Interleaving StringEdit Distance.

posted @ 2015-09-18 04:31  Dylan_Java_NYC  阅读(201)  评论(0编辑  收藏  举报