Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 115. Distinct Subsequences #111

Open
Woodyiiiiiii opened this issue May 8, 2022 · 0 comments
Open

Leetcode 115. Distinct Subsequences #111

Woodyiiiiiii opened this issue May 8, 2022 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

如何推出递归方程?可以举例反证。

class Solution {
    public int numDistinct(String s, String t) {
        
        int m = s.length(), n = t.length();
        int[][] dp = new int[m + 1][n + 1];
        
        // init
        for (int i = 0; i <= m; ++i) {
            dp[i][0] = 1;
        }
        for (int j = 1; j <= n; ++j) {
            dp[0][j] = 0;
        }
        
        // formula
        for (int i = 1; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (s.charAt(i - 1) != t.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j];
                } else {
                    // 根据是否匹配
                    // 比如abb和ab,dp[i - 1][j - 1]即选择不匹配,为ab和a;
                    // dp[i - 1][j]则为匹配,可能性有ab和ab
                    dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
                }
            }
        }
        
        return dp[m][n];
        
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant