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];
    }
};
相关推荐
亮亮爱刷题9 天前
飞往大厂梦之算法提升-7
数据结构·算法·leetcode·动态规划
zmuy9 天前
124. 二叉树中的最大路径和
数据结构·算法·leetcode
chao_7899 天前
滑动窗口题解——找到字符串中所有字母异位词【LeetCode】
数据结构·算法·leetcode
Alfred king9 天前
面试150跳跃游戏
python·leetcode·游戏·贪心算法
呆呆的小鳄鱼9 天前
leetcode:746. 使用最小花费爬楼梯
算法·leetcode·职场和发展
YuTaoShao9 天前
【LeetCode 热题 100】42. 接雨水——(解法一)前后缀分解
java·算法·leetcode·职场和发展
YuforiaCode10 天前
(LeetCode 面试经典 150 题) 27.移除元素
算法·leetcode·面试
呆呆的小鳄鱼10 天前
leetcode:98. 验证二叉搜索树
算法·leetcode·职场和发展
alphaTao10 天前
LeetCode 每日一题 2025/6/16-2025/6/22
算法·leetcode
YuTaoShao10 天前
【LeetCode 热题 100】11. 盛最多水的容器——Java双指针解法
java·算法·leetcode