leetcode 115. 不同的子序列

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

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

fij = fi - 1j + (si == tj ? fi - 1j - 1 : 0)

答案就是 fs.length() - 1t.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];
    }
};
相关推荐
白白白小纯1 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
圣保罗的大教堂3 小时前
leetcode 3517. 最小回文排列 I 中等
leetcode
alphaTao6 小时前
LeetCode 每日一题 2026/7/27-2026/8/2
python·算法·leetcode
Hi李耶12 小时前
【LeetCode】9-回文数
算法·leetcode·职场和发展
海绵天哥16 小时前
LeetCode Hot 100 | 链表(下)· 分组翻转与设计(C++ 题解)
c++·leetcode·链表
tkevinjd1 天前
力扣131-分割回文串
算法·leetcode·深度优先
zander2581 天前
LeetCode 78. 子集
算法·leetcode·深度优先
Tisfy1 天前
LeetCode 3014.输入单词需要的最少按键次数 I:遍历 / if-else计算(比纯数学公式写起来麻烦但好想)
数学·算法·leetcode·字符串·题解·贪心
tkevinjd2 天前
力扣239-滑动窗口最大值
算法·leetcode·职场和发展
圣保罗的大教堂2 天前
leetcode 628. 三个数的最大乘积 简单
leetcode