leetcode 115. 不同的子序列

题目:115. 不同的子序列 - 力扣(LeetCode)

动态规划问题,f[i][j]表示s的第i个元素匹配到t的第j个元素,有多少种结果

f[i][j] = f[i - 1][j] + (s[i] == t[j] ? f[i - 1][j - 1] : 0)

答案就是 f[s.length() - 1][t.length() - 1]

cpp 复制代码
#define _MAX_ (1000000007)
class Solution {
public:
    int numDistinct(string s, string t) {
        int n = (int) s.length();
        int m = (int) t.length();
        uint32_t** f = (uint32_t**) malloc(n * sizeof(uint32_t*));
        for (int i = 0; i < n; i++) {
            f[i] = (uint32_t*) malloc(m * sizeof(uint32_t));
        }
        for (int i = 0; i < n; i++) {
            if (s[i] == t[0]) {
                f[i][0] = 1;
            } else {
                f[i][0] = 0;
            }
            if (i > 0) {
                f[i][0] += f[i - 1][0];
                uint32_t a = f[i][0];
                uint32_t b = f[i - 1][0];
                if (f[i][0] >= _MAX_) {
                    f[i][0] %= _MAX_;
                }
            }
            for (int j = 1; j < m; j++) {
                if (i > 0) {
                    f[i][j] = f[i - 1][j];
                } else {
                    f[i][j] = 0;
                }
                if (s[i] == t[j] && i > 0) {
                    f[i][j] += f[i - 1][j - 1];
                    if (f[i][j] >= _MAX_) {
                        f[i][j] %= _MAX_;
                    }
                }
            }
        }
//        for (int i = 0; i < n; i++) {
//            for (int j = 0; j < m; j++) {
//                printf("%d ", f[i][j]);
//            }
//            printf("\n");
//        }
        return f[n - 1][m - 1];
    }
};
相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
元亓亓亓2 天前
LeetCode热题100--105. 从前序与中序遍历序列构造二叉树--中等
算法·leetcode·职场和发展
仙俊红3 天前
LeetCode每日一题,20250914
算法·leetcode·职场和发展
_不会dp不改名_3 天前
leetcode_21 合并两个有序链表
算法·leetcode·链表
吃着火锅x唱着歌3 天前
LeetCode 3302.字典序最小的合法序列
leetcode
睡不醒的kun3 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌3 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
爱编程的化学家3 天前
代码随想录算法训练营第十一天--二叉树2 || 226.翻转二叉树 / 101.对称二叉树 / 104.二叉树的最大深度 / 111.二叉树的最小深度
数据结构·c++·算法·leetcode·二叉树·代码随想录
吃着火锅x唱着歌3 天前
LeetCode 1446.连续字符
算法·leetcode·职场和发展
愚润求学3 天前
【贪心算法】day10
c++·算法·leetcode·贪心算法