zoukankan      html  css  js  c++  java
  • Java for LeetCode 115 Distinct Subsequences【HARD】

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

    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).

    Here is an example:
    S = "rabbbit", T = "rabbit"

    Return 3.

    解题思路:

    dp问题,弄清递推公式即可,参考Distinct Subsequences@LeetCode ,JAVA实现如下:

    	public int numDistinct(String s, String t) {
    		if (t.length() == 0)
    			return 1;
    		int[] dp = new int[t.length() + 1];
    		dp[0] = 1;
    		for (int i = 0; i < s.length(); i++) {
    			int last = 1;
    			for (int j = 0; j < t.length(); j++) {
    				if (dp[j] == 0)
    					break;
    				int temp = dp[j + 1];
    				if (s.charAt(i) == t.charAt(j))
    					dp[j + 1] += last;
    				last = temp;
    			}
    		}
    		return dp[t.length()];
    	}
    
  • 相关阅读:
    ARC081F Flip and Rectangles
    LCA
    Tarjan
    2020牛客暑期多校六
    状压DP
    操作系统
    JAVA期末复习
    D. Yet Another Yet Another Task (区间最值)
    构造
    Codeforces Round #641 (Div. 2)
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4525608.html
Copyright © 2011-2022 走看看