**LeetCode-Distinct Subsequences

28 篇文章 0 订阅

dp!感觉地推公式好难想 用了一个m*n矩阵 下面是讲解 递推看了讲解感觉能看懂 但是在0位置多出一行一列 并且初始化的数并不能很直观的想出来

/**
 * Solution (DP):
 * We keep a m*n matrix and scanning through string S, while
 * m = T.length() + 1 and n = S.length() + 1
 * and each cell in matrix Path[i][j] means the number of distinct subsequences of 
 * T.substr(1...i) in S(1...j)
 * 
 * Path[i][j] = Path[i][j-1]            (discard S[j])
 *              +     Path[i-1][j-1]    (S[j] == T[i] and we are going to use S[j])
 *                 or 0                 (S[j] != T[i] so we could not use S[j])
 * while Path[0][j] = 1 and Path[i][0] = 0.
 */

public class Solution {
    public int numDistinct(String s, String t) {
        if ( s == null || t == null )
            return 0;
        int m = s.length();
        int n = t.length();
        if ( m < n )
            return 0;
        int [][] res = new int [ n + 1 ][ m + 1 ];
        for ( int i = 0; i <= m; i ++ )
            res [ 0 ][ i ] = 1;
        for ( int i = 1; i <= n; i ++ ){
            for ( int j = 1; j <= m; j ++ ){
                if ( s.charAt( j - 1 ) == t.charAt( i - 1 ) )
                    res [ i ][ j ] = res [ i ][ j - 1 ] + res [ i - 1 ][ j - 1 ];
                else 
                    res [ i ][ j ] = res [ i ][ j - 1 ];
            }
        }
        return res [ n ][ m ];
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值