LeetCode 115. Distinct Subsequences(子序列数量)

51 篇文章 0 订阅
9 篇文章 0 订阅

原题网址:https://leetcode.com/problems/distinct-subsequences/

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.

方法一:递归+记忆化搜索,但会内存溢出。

public class Solution {
    boolean[][] visit;
    int[][] nums;
    public int numDistinct(String s, String t) {
        if (visit == null) {
            visit = new boolean[s.length() + 1][t.length() + 1];
            nums = new int[s.length() + 1][t.length() + 1];
        }
        if (visit[s.length()][t.length()]) return nums[s.length()][t.length()];
        if (t.length() == 0) return 1;
        if (s.length() < t.length()) return 0;
        if (s.charAt(s.length() - 1) == t.charAt(t.length() - 1)) {
            nums[s.length()][t.length()] = numDistinct(s.substring(0, s.length() - 1), t.substring(0, t.length() - 1));
        }
        nums[s.length()][t.length()] += numDistinct(s.substring(0, s.length() - 1), t);
        visit[s.length()][t.length()] = true;
        return nums[s.length()][t.length()];
    }
}

方法二:动态规划。

public class Solution {
    public int numDistinct(String s, String t) {
        char[] sa = s.toCharArray();
        char[] ta = t.toCharArray();
        if (sa.length == 0 || ta.length == 0) return 0;
        int[][] nums = new int[ta.length+1][sa.length+1];
        for(int j=0; j<=sa.length; j++) nums[0][j] = 1;
        for(int i=1; i<=ta.length; i++) {
            for(int j=1; j<=sa.length; j++) {
                nums[i][j] = nums[i][j-1];
                if (sa[j-1] == ta[i-1]) nums[i][j] += nums[i-1][j-1];
            }
        }
        return nums[ta.length][sa.length];
    }
}

方法三:动态规划,优化内存。

public class Solution {
    public int numDistinct(String s, String t) {
        if (t.length() == 0) return 1;
        if (s.length() < t.length()) return 0;
        char[] sa = s.toCharArray();
        char[] ta = t.toCharArray();
        int[] nums = new int[ta.length + 1];
        nums[0] = 1;
        for(int i = 1; i <= sa.length; i++) {
            int[] next = new int[ta.length + 1];
            next[0] = 1;
            for(int j = 1; j <= ta.length; j++) {
                next[j] = nums[j];
                if (sa[i - 1] == ta[j - 1]) {
                    next[j] += nums[j - 1];
                }
            }
            nums = next;
        }
        return nums[ta.length];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值